##// END OF EJS Templates
clone: rename "rev" to "revs" since there can be many...
Martin von Zweigbergk -
r37279:54435fd0 default
parent child Browse files
Show More
@@ -1,3659 +1,3659 b''
1 # mq.py - patch queues for mercurial
1 # mq.py - patch queues for mercurial
2 #
2 #
3 # Copyright 2005, 2006 Chris Mason <mason@suse.com>
3 # Copyright 2005, 2006 Chris Mason <mason@suse.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 '''manage a stack of patches
8 '''manage a stack of patches
9
9
10 This extension lets you work with a stack of patches in a Mercurial
10 This extension lets you work with a stack of patches in a Mercurial
11 repository. It manages two stacks of patches - all known patches, and
11 repository. It manages two stacks of patches - all known patches, and
12 applied patches (subset of known patches).
12 applied patches (subset of known patches).
13
13
14 Known patches are represented as patch files in the .hg/patches
14 Known patches are represented as patch files in the .hg/patches
15 directory. Applied patches are both patch files and changesets.
15 directory. Applied patches are both patch files and changesets.
16
16
17 Common tasks (use :hg:`help COMMAND` for more details)::
17 Common tasks (use :hg:`help COMMAND` for more details)::
18
18
19 create new patch qnew
19 create new patch qnew
20 import existing patch qimport
20 import existing patch qimport
21
21
22 print patch series qseries
22 print patch series qseries
23 print applied patches qapplied
23 print applied patches qapplied
24
24
25 add known patch to applied stack qpush
25 add known patch to applied stack qpush
26 remove patch from applied stack qpop
26 remove patch from applied stack qpop
27 refresh contents of top applied patch qrefresh
27 refresh contents of top applied patch qrefresh
28
28
29 By default, mq will automatically use git patches when required to
29 By default, mq will automatically use git patches when required to
30 avoid losing file mode changes, copy records, binary files or empty
30 avoid losing file mode changes, copy records, binary files or empty
31 files creations or deletions. This behavior can be configured with::
31 files creations or deletions. This behavior can be configured with::
32
32
33 [mq]
33 [mq]
34 git = auto/keep/yes/no
34 git = auto/keep/yes/no
35
35
36 If set to 'keep', mq will obey the [diff] section configuration while
36 If set to 'keep', mq will obey the [diff] section configuration while
37 preserving existing git patches upon qrefresh. If set to 'yes' or
37 preserving existing git patches upon qrefresh. If set to 'yes' or
38 'no', mq will override the [diff] section and always generate git or
38 'no', mq will override the [diff] section and always generate git or
39 regular patches, possibly losing data in the second case.
39 regular patches, possibly losing data in the second case.
40
40
41 It may be desirable for mq changesets to be kept in the secret phase (see
41 It may be desirable for mq changesets to be kept in the secret phase (see
42 :hg:`help phases`), which can be enabled with the following setting::
42 :hg:`help phases`), which can be enabled with the following setting::
43
43
44 [mq]
44 [mq]
45 secret = True
45 secret = True
46
46
47 You will by default be managing a patch queue named "patches". You can
47 You will by default be managing a patch queue named "patches". You can
48 create other, independent patch queues with the :hg:`qqueue` command.
48 create other, independent patch queues with the :hg:`qqueue` command.
49
49
50 If the working directory contains uncommitted files, qpush, qpop and
50 If the working directory contains uncommitted files, qpush, qpop and
51 qgoto abort immediately. If -f/--force is used, the changes are
51 qgoto abort immediately. If -f/--force is used, the changes are
52 discarded. Setting::
52 discarded. Setting::
53
53
54 [mq]
54 [mq]
55 keepchanges = True
55 keepchanges = True
56
56
57 make them behave as if --keep-changes were passed, and non-conflicting
57 make them behave as if --keep-changes were passed, and non-conflicting
58 local changes will be tolerated and preserved. If incompatible options
58 local changes will be tolerated and preserved. If incompatible options
59 such as -f/--force or --exact are passed, this setting is ignored.
59 such as -f/--force or --exact are passed, this setting is ignored.
60
60
61 This extension used to provide a strip command. This command now lives
61 This extension used to provide a strip command. This command now lives
62 in the strip extension.
62 in the strip extension.
63 '''
63 '''
64
64
65 from __future__ import absolute_import, print_function
65 from __future__ import absolute_import, print_function
66
66
67 import errno
67 import errno
68 import os
68 import os
69 import re
69 import re
70 import shutil
70 import shutil
71 from mercurial.i18n import _
71 from mercurial.i18n import _
72 from mercurial.node import (
72 from mercurial.node import (
73 bin,
73 bin,
74 hex,
74 hex,
75 nullid,
75 nullid,
76 nullrev,
76 nullrev,
77 short,
77 short,
78 )
78 )
79 from mercurial import (
79 from mercurial import (
80 cmdutil,
80 cmdutil,
81 commands,
81 commands,
82 dirstateguard,
82 dirstateguard,
83 encoding,
83 encoding,
84 error,
84 error,
85 extensions,
85 extensions,
86 hg,
86 hg,
87 localrepo,
87 localrepo,
88 lock as lockmod,
88 lock as lockmod,
89 logcmdutil,
89 logcmdutil,
90 patch as patchmod,
90 patch as patchmod,
91 phases,
91 phases,
92 pycompat,
92 pycompat,
93 registrar,
93 registrar,
94 revsetlang,
94 revsetlang,
95 scmutil,
95 scmutil,
96 smartset,
96 smartset,
97 subrepoutil,
97 subrepoutil,
98 util,
98 util,
99 vfs as vfsmod,
99 vfs as vfsmod,
100 )
100 )
101 from mercurial.utils import (
101 from mercurial.utils import (
102 dateutil,
102 dateutil,
103 stringutil,
103 stringutil,
104 )
104 )
105
105
106 release = lockmod.release
106 release = lockmod.release
107 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
107 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
108
108
109 cmdtable = {}
109 cmdtable = {}
110 command = registrar.command(cmdtable)
110 command = registrar.command(cmdtable)
111 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
111 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
112 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
112 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
113 # be specifying the version(s) of Mercurial they are tested with, or
113 # be specifying the version(s) of Mercurial they are tested with, or
114 # leave the attribute unspecified.
114 # leave the attribute unspecified.
115 testedwith = 'ships-with-hg-core'
115 testedwith = 'ships-with-hg-core'
116
116
117 configtable = {}
117 configtable = {}
118 configitem = registrar.configitem(configtable)
118 configitem = registrar.configitem(configtable)
119
119
120 configitem('mq', 'git',
120 configitem('mq', 'git',
121 default='auto',
121 default='auto',
122 )
122 )
123 configitem('mq', 'keepchanges',
123 configitem('mq', 'keepchanges',
124 default=False,
124 default=False,
125 )
125 )
126 configitem('mq', 'plain',
126 configitem('mq', 'plain',
127 default=False,
127 default=False,
128 )
128 )
129 configitem('mq', 'secret',
129 configitem('mq', 'secret',
130 default=False,
130 default=False,
131 )
131 )
132
132
133 # force load strip extension formerly included in mq and import some utility
133 # force load strip extension formerly included in mq and import some utility
134 try:
134 try:
135 stripext = extensions.find('strip')
135 stripext = extensions.find('strip')
136 except KeyError:
136 except KeyError:
137 # note: load is lazy so we could avoid the try-except,
137 # note: load is lazy so we could avoid the try-except,
138 # but I (marmoute) prefer this explicit code.
138 # but I (marmoute) prefer this explicit code.
139 class dummyui(object):
139 class dummyui(object):
140 def debug(self, msg):
140 def debug(self, msg):
141 pass
141 pass
142 stripext = extensions.load(dummyui(), 'strip', '')
142 stripext = extensions.load(dummyui(), 'strip', '')
143
143
144 strip = stripext.strip
144 strip = stripext.strip
145 checksubstate = stripext.checksubstate
145 checksubstate = stripext.checksubstate
146 checklocalchanges = stripext.checklocalchanges
146 checklocalchanges = stripext.checklocalchanges
147
147
148
148
149 # Patch names looks like unix-file names.
149 # Patch names looks like unix-file names.
150 # They must be joinable with queue directory and result in the patch path.
150 # They must be joinable with queue directory and result in the patch path.
151 normname = util.normpath
151 normname = util.normpath
152
152
153 class statusentry(object):
153 class statusentry(object):
154 def __init__(self, node, name):
154 def __init__(self, node, name):
155 self.node, self.name = node, name
155 self.node, self.name = node, name
156
156
157 def __bytes__(self):
157 def __bytes__(self):
158 return hex(self.node) + ':' + self.name
158 return hex(self.node) + ':' + self.name
159
159
160 __str__ = encoding.strmethod(__bytes__)
160 __str__ = encoding.strmethod(__bytes__)
161 __repr__ = encoding.strmethod(__bytes__)
161 __repr__ = encoding.strmethod(__bytes__)
162
162
163 # The order of the headers in 'hg export' HG patches:
163 # The order of the headers in 'hg export' HG patches:
164 HGHEADERS = [
164 HGHEADERS = [
165 # '# HG changeset patch',
165 # '# HG changeset patch',
166 '# User ',
166 '# User ',
167 '# Date ',
167 '# Date ',
168 '# ',
168 '# ',
169 '# Branch ',
169 '# Branch ',
170 '# Node ID ',
170 '# Node ID ',
171 '# Parent ', # can occur twice for merges - but that is not relevant for mq
171 '# Parent ', # can occur twice for merges - but that is not relevant for mq
172 ]
172 ]
173 # The order of headers in plain 'mail style' patches:
173 # The order of headers in plain 'mail style' patches:
174 PLAINHEADERS = {
174 PLAINHEADERS = {
175 'from': 0,
175 'from': 0,
176 'date': 1,
176 'date': 1,
177 'subject': 2,
177 'subject': 2,
178 }
178 }
179
179
180 def inserthgheader(lines, header, value):
180 def inserthgheader(lines, header, value):
181 """Assuming lines contains a HG patch header, add a header line with value.
181 """Assuming lines contains a HG patch header, add a header line with value.
182 >>> try: inserthgheader([], b'# Date ', b'z')
182 >>> try: inserthgheader([], b'# Date ', b'z')
183 ... except ValueError as inst: print("oops")
183 ... except ValueError as inst: print("oops")
184 oops
184 oops
185 >>> inserthgheader([b'# HG changeset patch'], b'# Date ', b'z')
185 >>> inserthgheader([b'# HG changeset patch'], b'# Date ', b'z')
186 ['# HG changeset patch', '# Date z']
186 ['# HG changeset patch', '# Date z']
187 >>> inserthgheader([b'# HG changeset patch', b''], b'# Date ', b'z')
187 >>> inserthgheader([b'# HG changeset patch', b''], b'# Date ', b'z')
188 ['# HG changeset patch', '# Date z', '']
188 ['# HG changeset patch', '# Date z', '']
189 >>> inserthgheader([b'# HG changeset patch', b'# User y'], b'# Date ', b'z')
189 >>> inserthgheader([b'# HG changeset patch', b'# User y'], b'# Date ', b'z')
190 ['# HG changeset patch', '# User y', '# Date z']
190 ['# HG changeset patch', '# User y', '# Date z']
191 >>> inserthgheader([b'# HG changeset patch', b'# Date x', b'# User y'],
191 >>> inserthgheader([b'# HG changeset patch', b'# Date x', b'# User y'],
192 ... b'# User ', b'z')
192 ... b'# User ', b'z')
193 ['# HG changeset patch', '# Date x', '# User z']
193 ['# HG changeset patch', '# Date x', '# User z']
194 >>> inserthgheader([b'# HG changeset patch', b'# Date y'], b'# Date ', b'z')
194 >>> inserthgheader([b'# HG changeset patch', b'# Date y'], b'# Date ', b'z')
195 ['# HG changeset patch', '# Date z']
195 ['# HG changeset patch', '# Date z']
196 >>> inserthgheader([b'# HG changeset patch', b'', b'# Date y'],
196 >>> inserthgheader([b'# HG changeset patch', b'', b'# Date y'],
197 ... b'# Date ', b'z')
197 ... b'# Date ', b'z')
198 ['# HG changeset patch', '# Date z', '', '# Date y']
198 ['# HG changeset patch', '# Date z', '', '# Date y']
199 >>> inserthgheader([b'# HG changeset patch', b'# Parent y'],
199 >>> inserthgheader([b'# HG changeset patch', b'# Parent y'],
200 ... b'# Date ', b'z')
200 ... b'# Date ', b'z')
201 ['# HG changeset patch', '# Date z', '# Parent y']
201 ['# HG changeset patch', '# Date z', '# Parent y']
202 """
202 """
203 start = lines.index('# HG changeset patch') + 1
203 start = lines.index('# HG changeset patch') + 1
204 newindex = HGHEADERS.index(header)
204 newindex = HGHEADERS.index(header)
205 bestpos = len(lines)
205 bestpos = len(lines)
206 for i in range(start, len(lines)):
206 for i in range(start, len(lines)):
207 line = lines[i]
207 line = lines[i]
208 if not line.startswith('# '):
208 if not line.startswith('# '):
209 bestpos = min(bestpos, i)
209 bestpos = min(bestpos, i)
210 break
210 break
211 for lineindex, h in enumerate(HGHEADERS):
211 for lineindex, h in enumerate(HGHEADERS):
212 if line.startswith(h):
212 if line.startswith(h):
213 if lineindex == newindex:
213 if lineindex == newindex:
214 lines[i] = header + value
214 lines[i] = header + value
215 return lines
215 return lines
216 if lineindex > newindex:
216 if lineindex > newindex:
217 bestpos = min(bestpos, i)
217 bestpos = min(bestpos, i)
218 break # next line
218 break # next line
219 lines.insert(bestpos, header + value)
219 lines.insert(bestpos, header + value)
220 return lines
220 return lines
221
221
222 def insertplainheader(lines, header, value):
222 def insertplainheader(lines, header, value):
223 """For lines containing a plain patch header, add a header line with value.
223 """For lines containing a plain patch header, add a header line with value.
224 >>> insertplainheader([], b'Date', b'z')
224 >>> insertplainheader([], b'Date', b'z')
225 ['Date: z']
225 ['Date: z']
226 >>> insertplainheader([b''], b'Date', b'z')
226 >>> insertplainheader([b''], b'Date', b'z')
227 ['Date: z', '']
227 ['Date: z', '']
228 >>> insertplainheader([b'x'], b'Date', b'z')
228 >>> insertplainheader([b'x'], b'Date', b'z')
229 ['Date: z', '', 'x']
229 ['Date: z', '', 'x']
230 >>> insertplainheader([b'From: y', b'x'], b'Date', b'z')
230 >>> insertplainheader([b'From: y', b'x'], b'Date', b'z')
231 ['From: y', 'Date: z', '', 'x']
231 ['From: y', 'Date: z', '', 'x']
232 >>> insertplainheader([b' date : x', b' from : y', b''], b'From', b'z')
232 >>> insertplainheader([b' date : x', b' from : y', b''], b'From', b'z')
233 [' date : x', 'From: z', '']
233 [' date : x', 'From: z', '']
234 >>> insertplainheader([b'', b'Date: y'], b'Date', b'z')
234 >>> insertplainheader([b'', b'Date: y'], b'Date', b'z')
235 ['Date: z', '', 'Date: y']
235 ['Date: z', '', 'Date: y']
236 >>> insertplainheader([b'foo: bar', b'DATE: z', b'x'], b'From', b'y')
236 >>> insertplainheader([b'foo: bar', b'DATE: z', b'x'], b'From', b'y')
237 ['From: y', 'foo: bar', 'DATE: z', '', 'x']
237 ['From: y', 'foo: bar', 'DATE: z', '', 'x']
238 """
238 """
239 newprio = PLAINHEADERS[header.lower()]
239 newprio = PLAINHEADERS[header.lower()]
240 bestpos = len(lines)
240 bestpos = len(lines)
241 for i, line in enumerate(lines):
241 for i, line in enumerate(lines):
242 if ':' in line:
242 if ':' in line:
243 lheader = line.split(':', 1)[0].strip().lower()
243 lheader = line.split(':', 1)[0].strip().lower()
244 lprio = PLAINHEADERS.get(lheader, newprio + 1)
244 lprio = PLAINHEADERS.get(lheader, newprio + 1)
245 if lprio == newprio:
245 if lprio == newprio:
246 lines[i] = '%s: %s' % (header, value)
246 lines[i] = '%s: %s' % (header, value)
247 return lines
247 return lines
248 if lprio > newprio and i < bestpos:
248 if lprio > newprio and i < bestpos:
249 bestpos = i
249 bestpos = i
250 else:
250 else:
251 if line:
251 if line:
252 lines.insert(i, '')
252 lines.insert(i, '')
253 if i < bestpos:
253 if i < bestpos:
254 bestpos = i
254 bestpos = i
255 break
255 break
256 lines.insert(bestpos, '%s: %s' % (header, value))
256 lines.insert(bestpos, '%s: %s' % (header, value))
257 return lines
257 return lines
258
258
259 class patchheader(object):
259 class patchheader(object):
260 def __init__(self, pf, plainmode=False):
260 def __init__(self, pf, plainmode=False):
261 def eatdiff(lines):
261 def eatdiff(lines):
262 while lines:
262 while lines:
263 l = lines[-1]
263 l = lines[-1]
264 if (l.startswith("diff -") or
264 if (l.startswith("diff -") or
265 l.startswith("Index:") or
265 l.startswith("Index:") or
266 l.startswith("===========")):
266 l.startswith("===========")):
267 del lines[-1]
267 del lines[-1]
268 else:
268 else:
269 break
269 break
270 def eatempty(lines):
270 def eatempty(lines):
271 while lines:
271 while lines:
272 if not lines[-1].strip():
272 if not lines[-1].strip():
273 del lines[-1]
273 del lines[-1]
274 else:
274 else:
275 break
275 break
276
276
277 message = []
277 message = []
278 comments = []
278 comments = []
279 user = None
279 user = None
280 date = None
280 date = None
281 parent = None
281 parent = None
282 format = None
282 format = None
283 subject = None
283 subject = None
284 branch = None
284 branch = None
285 nodeid = None
285 nodeid = None
286 diffstart = 0
286 diffstart = 0
287
287
288 for line in open(pf, 'rb'):
288 for line in open(pf, 'rb'):
289 line = line.rstrip()
289 line = line.rstrip()
290 if (line.startswith('diff --git')
290 if (line.startswith('diff --git')
291 or (diffstart and line.startswith('+++ '))):
291 or (diffstart and line.startswith('+++ '))):
292 diffstart = 2
292 diffstart = 2
293 break
293 break
294 diffstart = 0 # reset
294 diffstart = 0 # reset
295 if line.startswith("--- "):
295 if line.startswith("--- "):
296 diffstart = 1
296 diffstart = 1
297 continue
297 continue
298 elif format == "hgpatch":
298 elif format == "hgpatch":
299 # parse values when importing the result of an hg export
299 # parse values when importing the result of an hg export
300 if line.startswith("# User "):
300 if line.startswith("# User "):
301 user = line[7:]
301 user = line[7:]
302 elif line.startswith("# Date "):
302 elif line.startswith("# Date "):
303 date = line[7:]
303 date = line[7:]
304 elif line.startswith("# Parent "):
304 elif line.startswith("# Parent "):
305 parent = line[9:].lstrip() # handle double trailing space
305 parent = line[9:].lstrip() # handle double trailing space
306 elif line.startswith("# Branch "):
306 elif line.startswith("# Branch "):
307 branch = line[9:]
307 branch = line[9:]
308 elif line.startswith("# Node ID "):
308 elif line.startswith("# Node ID "):
309 nodeid = line[10:]
309 nodeid = line[10:]
310 elif not line.startswith("# ") and line:
310 elif not line.startswith("# ") and line:
311 message.append(line)
311 message.append(line)
312 format = None
312 format = None
313 elif line == '# HG changeset patch':
313 elif line == '# HG changeset patch':
314 message = []
314 message = []
315 format = "hgpatch"
315 format = "hgpatch"
316 elif (format != "tagdone" and (line.startswith("Subject: ") or
316 elif (format != "tagdone" and (line.startswith("Subject: ") or
317 line.startswith("subject: "))):
317 line.startswith("subject: "))):
318 subject = line[9:]
318 subject = line[9:]
319 format = "tag"
319 format = "tag"
320 elif (format != "tagdone" and (line.startswith("From: ") or
320 elif (format != "tagdone" and (line.startswith("From: ") or
321 line.startswith("from: "))):
321 line.startswith("from: "))):
322 user = line[6:]
322 user = line[6:]
323 format = "tag"
323 format = "tag"
324 elif (format != "tagdone" and (line.startswith("Date: ") or
324 elif (format != "tagdone" and (line.startswith("Date: ") or
325 line.startswith("date: "))):
325 line.startswith("date: "))):
326 date = line[6:]
326 date = line[6:]
327 format = "tag"
327 format = "tag"
328 elif format == "tag" and line == "":
328 elif format == "tag" and line == "":
329 # when looking for tags (subject: from: etc) they
329 # when looking for tags (subject: from: etc) they
330 # end once you find a blank line in the source
330 # end once you find a blank line in the source
331 format = "tagdone"
331 format = "tagdone"
332 elif message or line:
332 elif message or line:
333 message.append(line)
333 message.append(line)
334 comments.append(line)
334 comments.append(line)
335
335
336 eatdiff(message)
336 eatdiff(message)
337 eatdiff(comments)
337 eatdiff(comments)
338 # Remember the exact starting line of the patch diffs before consuming
338 # Remember the exact starting line of the patch diffs before consuming
339 # empty lines, for external use by TortoiseHg and others
339 # empty lines, for external use by TortoiseHg and others
340 self.diffstartline = len(comments)
340 self.diffstartline = len(comments)
341 eatempty(message)
341 eatempty(message)
342 eatempty(comments)
342 eatempty(comments)
343
343
344 # make sure message isn't empty
344 # make sure message isn't empty
345 if format and format.startswith("tag") and subject:
345 if format and format.startswith("tag") and subject:
346 message.insert(0, subject)
346 message.insert(0, subject)
347
347
348 self.message = message
348 self.message = message
349 self.comments = comments
349 self.comments = comments
350 self.user = user
350 self.user = user
351 self.date = date
351 self.date = date
352 self.parent = parent
352 self.parent = parent
353 # nodeid and branch are for external use by TortoiseHg and others
353 # nodeid and branch are for external use by TortoiseHg and others
354 self.nodeid = nodeid
354 self.nodeid = nodeid
355 self.branch = branch
355 self.branch = branch
356 self.haspatch = diffstart > 1
356 self.haspatch = diffstart > 1
357 self.plainmode = (plainmode or
357 self.plainmode = (plainmode or
358 '# HG changeset patch' not in self.comments and
358 '# HG changeset patch' not in self.comments and
359 any(c.startswith('Date: ') or
359 any(c.startswith('Date: ') or
360 c.startswith('From: ')
360 c.startswith('From: ')
361 for c in self.comments))
361 for c in self.comments))
362
362
363 def setuser(self, user):
363 def setuser(self, user):
364 try:
364 try:
365 inserthgheader(self.comments, '# User ', user)
365 inserthgheader(self.comments, '# User ', user)
366 except ValueError:
366 except ValueError:
367 if self.plainmode:
367 if self.plainmode:
368 insertplainheader(self.comments, 'From', user)
368 insertplainheader(self.comments, 'From', user)
369 else:
369 else:
370 tmp = ['# HG changeset patch', '# User ' + user]
370 tmp = ['# HG changeset patch', '# User ' + user]
371 self.comments = tmp + self.comments
371 self.comments = tmp + self.comments
372 self.user = user
372 self.user = user
373
373
374 def setdate(self, date):
374 def setdate(self, date):
375 try:
375 try:
376 inserthgheader(self.comments, '# Date ', date)
376 inserthgheader(self.comments, '# Date ', date)
377 except ValueError:
377 except ValueError:
378 if self.plainmode:
378 if self.plainmode:
379 insertplainheader(self.comments, 'Date', date)
379 insertplainheader(self.comments, 'Date', date)
380 else:
380 else:
381 tmp = ['# HG changeset patch', '# Date ' + date]
381 tmp = ['# HG changeset patch', '# Date ' + date]
382 self.comments = tmp + self.comments
382 self.comments = tmp + self.comments
383 self.date = date
383 self.date = date
384
384
385 def setparent(self, parent):
385 def setparent(self, parent):
386 try:
386 try:
387 inserthgheader(self.comments, '# Parent ', parent)
387 inserthgheader(self.comments, '# Parent ', parent)
388 except ValueError:
388 except ValueError:
389 if not self.plainmode:
389 if not self.plainmode:
390 tmp = ['# HG changeset patch', '# Parent ' + parent]
390 tmp = ['# HG changeset patch', '# Parent ' + parent]
391 self.comments = tmp + self.comments
391 self.comments = tmp + self.comments
392 self.parent = parent
392 self.parent = parent
393
393
394 def setmessage(self, message):
394 def setmessage(self, message):
395 if self.comments:
395 if self.comments:
396 self._delmsg()
396 self._delmsg()
397 self.message = [message]
397 self.message = [message]
398 if message:
398 if message:
399 if self.plainmode and self.comments and self.comments[-1]:
399 if self.plainmode and self.comments and self.comments[-1]:
400 self.comments.append('')
400 self.comments.append('')
401 self.comments.append(message)
401 self.comments.append(message)
402
402
403 def __bytes__(self):
403 def __bytes__(self):
404 s = '\n'.join(self.comments).rstrip()
404 s = '\n'.join(self.comments).rstrip()
405 if not s:
405 if not s:
406 return ''
406 return ''
407 return s + '\n\n'
407 return s + '\n\n'
408
408
409 __str__ = encoding.strmethod(__bytes__)
409 __str__ = encoding.strmethod(__bytes__)
410
410
411 def _delmsg(self):
411 def _delmsg(self):
412 '''Remove existing message, keeping the rest of the comments fields.
412 '''Remove existing message, keeping the rest of the comments fields.
413 If comments contains 'subject: ', message will prepend
413 If comments contains 'subject: ', message will prepend
414 the field and a blank line.'''
414 the field and a blank line.'''
415 if self.message:
415 if self.message:
416 subj = 'subject: ' + self.message[0].lower()
416 subj = 'subject: ' + self.message[0].lower()
417 for i in xrange(len(self.comments)):
417 for i in xrange(len(self.comments)):
418 if subj == self.comments[i].lower():
418 if subj == self.comments[i].lower():
419 del self.comments[i]
419 del self.comments[i]
420 self.message = self.message[2:]
420 self.message = self.message[2:]
421 break
421 break
422 ci = 0
422 ci = 0
423 for mi in self.message:
423 for mi in self.message:
424 while mi != self.comments[ci]:
424 while mi != self.comments[ci]:
425 ci += 1
425 ci += 1
426 del self.comments[ci]
426 del self.comments[ci]
427
427
428 def newcommit(repo, phase, *args, **kwargs):
428 def newcommit(repo, phase, *args, **kwargs):
429 """helper dedicated to ensure a commit respect mq.secret setting
429 """helper dedicated to ensure a commit respect mq.secret setting
430
430
431 It should be used instead of repo.commit inside the mq source for operation
431 It should be used instead of repo.commit inside the mq source for operation
432 creating new changeset.
432 creating new changeset.
433 """
433 """
434 repo = repo.unfiltered()
434 repo = repo.unfiltered()
435 if phase is None:
435 if phase is None:
436 if repo.ui.configbool('mq', 'secret'):
436 if repo.ui.configbool('mq', 'secret'):
437 phase = phases.secret
437 phase = phases.secret
438 overrides = {('ui', 'allowemptycommit'): True}
438 overrides = {('ui', 'allowemptycommit'): True}
439 if phase is not None:
439 if phase is not None:
440 overrides[('phases', 'new-commit')] = phase
440 overrides[('phases', 'new-commit')] = phase
441 with repo.ui.configoverride(overrides, 'mq'):
441 with repo.ui.configoverride(overrides, 'mq'):
442 repo.ui.setconfig('ui', 'allowemptycommit', True)
442 repo.ui.setconfig('ui', 'allowemptycommit', True)
443 return repo.commit(*args, **kwargs)
443 return repo.commit(*args, **kwargs)
444
444
445 class AbortNoCleanup(error.Abort):
445 class AbortNoCleanup(error.Abort):
446 pass
446 pass
447
447
448 class queue(object):
448 class queue(object):
449 def __init__(self, ui, baseui, path, patchdir=None):
449 def __init__(self, ui, baseui, path, patchdir=None):
450 self.basepath = path
450 self.basepath = path
451 try:
451 try:
452 with open(os.path.join(path, 'patches.queue'), r'rb') as fh:
452 with open(os.path.join(path, 'patches.queue'), r'rb') as fh:
453 cur = fh.read().rstrip()
453 cur = fh.read().rstrip()
454
454
455 if not cur:
455 if not cur:
456 curpath = os.path.join(path, 'patches')
456 curpath = os.path.join(path, 'patches')
457 else:
457 else:
458 curpath = os.path.join(path, 'patches-' + cur)
458 curpath = os.path.join(path, 'patches-' + cur)
459 except IOError:
459 except IOError:
460 curpath = os.path.join(path, 'patches')
460 curpath = os.path.join(path, 'patches')
461 self.path = patchdir or curpath
461 self.path = patchdir or curpath
462 self.opener = vfsmod.vfs(self.path)
462 self.opener = vfsmod.vfs(self.path)
463 self.ui = ui
463 self.ui = ui
464 self.baseui = baseui
464 self.baseui = baseui
465 self.applieddirty = False
465 self.applieddirty = False
466 self.seriesdirty = False
466 self.seriesdirty = False
467 self.added = []
467 self.added = []
468 self.seriespath = "series"
468 self.seriespath = "series"
469 self.statuspath = "status"
469 self.statuspath = "status"
470 self.guardspath = "guards"
470 self.guardspath = "guards"
471 self.activeguards = None
471 self.activeguards = None
472 self.guardsdirty = False
472 self.guardsdirty = False
473 # Handle mq.git as a bool with extended values
473 # Handle mq.git as a bool with extended values
474 gitmode = ui.config('mq', 'git').lower()
474 gitmode = ui.config('mq', 'git').lower()
475 boolmode = stringutil.parsebool(gitmode)
475 boolmode = stringutil.parsebool(gitmode)
476 if boolmode is not None:
476 if boolmode is not None:
477 if boolmode:
477 if boolmode:
478 gitmode = 'yes'
478 gitmode = 'yes'
479 else:
479 else:
480 gitmode = 'no'
480 gitmode = 'no'
481 self.gitmode = gitmode
481 self.gitmode = gitmode
482 # deprecated config: mq.plain
482 # deprecated config: mq.plain
483 self.plainmode = ui.configbool('mq', 'plain')
483 self.plainmode = ui.configbool('mq', 'plain')
484 self.checkapplied = True
484 self.checkapplied = True
485
485
486 @util.propertycache
486 @util.propertycache
487 def applied(self):
487 def applied(self):
488 def parselines(lines):
488 def parselines(lines):
489 for l in lines:
489 for l in lines:
490 entry = l.split(':', 1)
490 entry = l.split(':', 1)
491 if len(entry) > 1:
491 if len(entry) > 1:
492 n, name = entry
492 n, name = entry
493 yield statusentry(bin(n), name)
493 yield statusentry(bin(n), name)
494 elif l.strip():
494 elif l.strip():
495 self.ui.warn(_('malformated mq status line: %s\n') % entry)
495 self.ui.warn(_('malformated mq status line: %s\n') % entry)
496 # else we ignore empty lines
496 # else we ignore empty lines
497 try:
497 try:
498 lines = self.opener.read(self.statuspath).splitlines()
498 lines = self.opener.read(self.statuspath).splitlines()
499 return list(parselines(lines))
499 return list(parselines(lines))
500 except IOError as e:
500 except IOError as e:
501 if e.errno == errno.ENOENT:
501 if e.errno == errno.ENOENT:
502 return []
502 return []
503 raise
503 raise
504
504
505 @util.propertycache
505 @util.propertycache
506 def fullseries(self):
506 def fullseries(self):
507 try:
507 try:
508 return self.opener.read(self.seriespath).splitlines()
508 return self.opener.read(self.seriespath).splitlines()
509 except IOError as e:
509 except IOError as e:
510 if e.errno == errno.ENOENT:
510 if e.errno == errno.ENOENT:
511 return []
511 return []
512 raise
512 raise
513
513
514 @util.propertycache
514 @util.propertycache
515 def series(self):
515 def series(self):
516 self.parseseries()
516 self.parseseries()
517 return self.series
517 return self.series
518
518
519 @util.propertycache
519 @util.propertycache
520 def seriesguards(self):
520 def seriesguards(self):
521 self.parseseries()
521 self.parseseries()
522 return self.seriesguards
522 return self.seriesguards
523
523
524 def invalidate(self):
524 def invalidate(self):
525 for a in 'applied fullseries series seriesguards'.split():
525 for a in 'applied fullseries series seriesguards'.split():
526 if a in self.__dict__:
526 if a in self.__dict__:
527 delattr(self, a)
527 delattr(self, a)
528 self.applieddirty = False
528 self.applieddirty = False
529 self.seriesdirty = False
529 self.seriesdirty = False
530 self.guardsdirty = False
530 self.guardsdirty = False
531 self.activeguards = None
531 self.activeguards = None
532
532
533 def diffopts(self, opts=None, patchfn=None, plain=False):
533 def diffopts(self, opts=None, patchfn=None, plain=False):
534 """Return diff options tweaked for this mq use, possibly upgrading to
534 """Return diff options tweaked for this mq use, possibly upgrading to
535 git format, and possibly plain and without lossy options."""
535 git format, and possibly plain and without lossy options."""
536 diffopts = patchmod.difffeatureopts(self.ui, opts,
536 diffopts = patchmod.difffeatureopts(self.ui, opts,
537 git=True, whitespace=not plain, formatchanging=not plain)
537 git=True, whitespace=not plain, formatchanging=not plain)
538 if self.gitmode == 'auto':
538 if self.gitmode == 'auto':
539 diffopts.upgrade = True
539 diffopts.upgrade = True
540 elif self.gitmode == 'keep':
540 elif self.gitmode == 'keep':
541 pass
541 pass
542 elif self.gitmode in ('yes', 'no'):
542 elif self.gitmode in ('yes', 'no'):
543 diffopts.git = self.gitmode == 'yes'
543 diffopts.git = self.gitmode == 'yes'
544 else:
544 else:
545 raise error.Abort(_('mq.git option can be auto/keep/yes/no'
545 raise error.Abort(_('mq.git option can be auto/keep/yes/no'
546 ' got %s') % self.gitmode)
546 ' got %s') % self.gitmode)
547 if patchfn:
547 if patchfn:
548 diffopts = self.patchopts(diffopts, patchfn)
548 diffopts = self.patchopts(diffopts, patchfn)
549 return diffopts
549 return diffopts
550
550
551 def patchopts(self, diffopts, *patches):
551 def patchopts(self, diffopts, *patches):
552 """Return a copy of input diff options with git set to true if
552 """Return a copy of input diff options with git set to true if
553 referenced patch is a git patch and should be preserved as such.
553 referenced patch is a git patch and should be preserved as such.
554 """
554 """
555 diffopts = diffopts.copy()
555 diffopts = diffopts.copy()
556 if not diffopts.git and self.gitmode == 'keep':
556 if not diffopts.git and self.gitmode == 'keep':
557 for patchfn in patches:
557 for patchfn in patches:
558 patchf = self.opener(patchfn, 'r')
558 patchf = self.opener(patchfn, 'r')
559 # if the patch was a git patch, refresh it as a git patch
559 # if the patch was a git patch, refresh it as a git patch
560 diffopts.git = any(line.startswith('diff --git')
560 diffopts.git = any(line.startswith('diff --git')
561 for line in patchf)
561 for line in patchf)
562 patchf.close()
562 patchf.close()
563 return diffopts
563 return diffopts
564
564
565 def join(self, *p):
565 def join(self, *p):
566 return os.path.join(self.path, *p)
566 return os.path.join(self.path, *p)
567
567
568 def findseries(self, patch):
568 def findseries(self, patch):
569 def matchpatch(l):
569 def matchpatch(l):
570 l = l.split('#', 1)[0]
570 l = l.split('#', 1)[0]
571 return l.strip() == patch
571 return l.strip() == patch
572 for index, l in enumerate(self.fullseries):
572 for index, l in enumerate(self.fullseries):
573 if matchpatch(l):
573 if matchpatch(l):
574 return index
574 return index
575 return None
575 return None
576
576
577 guard_re = re.compile(br'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
577 guard_re = re.compile(br'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
578
578
579 def parseseries(self):
579 def parseseries(self):
580 self.series = []
580 self.series = []
581 self.seriesguards = []
581 self.seriesguards = []
582 for l in self.fullseries:
582 for l in self.fullseries:
583 h = l.find('#')
583 h = l.find('#')
584 if h == -1:
584 if h == -1:
585 patch = l
585 patch = l
586 comment = ''
586 comment = ''
587 elif h == 0:
587 elif h == 0:
588 continue
588 continue
589 else:
589 else:
590 patch = l[:h]
590 patch = l[:h]
591 comment = l[h:]
591 comment = l[h:]
592 patch = patch.strip()
592 patch = patch.strip()
593 if patch:
593 if patch:
594 if patch in self.series:
594 if patch in self.series:
595 raise error.Abort(_('%s appears more than once in %s') %
595 raise error.Abort(_('%s appears more than once in %s') %
596 (patch, self.join(self.seriespath)))
596 (patch, self.join(self.seriespath)))
597 self.series.append(patch)
597 self.series.append(patch)
598 self.seriesguards.append(self.guard_re.findall(comment))
598 self.seriesguards.append(self.guard_re.findall(comment))
599
599
600 def checkguard(self, guard):
600 def checkguard(self, guard):
601 if not guard:
601 if not guard:
602 return _('guard cannot be an empty string')
602 return _('guard cannot be an empty string')
603 bad_chars = '# \t\r\n\f'
603 bad_chars = '# \t\r\n\f'
604 first = guard[0]
604 first = guard[0]
605 if first in '-+':
605 if first in '-+':
606 return (_('guard %r starts with invalid character: %r') %
606 return (_('guard %r starts with invalid character: %r') %
607 (guard, first))
607 (guard, first))
608 for c in bad_chars:
608 for c in bad_chars:
609 if c in guard:
609 if c in guard:
610 return _('invalid character in guard %r: %r') % (guard, c)
610 return _('invalid character in guard %r: %r') % (guard, c)
611
611
612 def setactive(self, guards):
612 def setactive(self, guards):
613 for guard in guards:
613 for guard in guards:
614 bad = self.checkguard(guard)
614 bad = self.checkguard(guard)
615 if bad:
615 if bad:
616 raise error.Abort(bad)
616 raise error.Abort(bad)
617 guards = sorted(set(guards))
617 guards = sorted(set(guards))
618 self.ui.debug('active guards: %s\n' % ' '.join(guards))
618 self.ui.debug('active guards: %s\n' % ' '.join(guards))
619 self.activeguards = guards
619 self.activeguards = guards
620 self.guardsdirty = True
620 self.guardsdirty = True
621
621
622 def active(self):
622 def active(self):
623 if self.activeguards is None:
623 if self.activeguards is None:
624 self.activeguards = []
624 self.activeguards = []
625 try:
625 try:
626 guards = self.opener.read(self.guardspath).split()
626 guards = self.opener.read(self.guardspath).split()
627 except IOError as err:
627 except IOError as err:
628 if err.errno != errno.ENOENT:
628 if err.errno != errno.ENOENT:
629 raise
629 raise
630 guards = []
630 guards = []
631 for i, guard in enumerate(guards):
631 for i, guard in enumerate(guards):
632 bad = self.checkguard(guard)
632 bad = self.checkguard(guard)
633 if bad:
633 if bad:
634 self.ui.warn('%s:%d: %s\n' %
634 self.ui.warn('%s:%d: %s\n' %
635 (self.join(self.guardspath), i + 1, bad))
635 (self.join(self.guardspath), i + 1, bad))
636 else:
636 else:
637 self.activeguards.append(guard)
637 self.activeguards.append(guard)
638 return self.activeguards
638 return self.activeguards
639
639
640 def setguards(self, idx, guards):
640 def setguards(self, idx, guards):
641 for g in guards:
641 for g in guards:
642 if len(g) < 2:
642 if len(g) < 2:
643 raise error.Abort(_('guard %r too short') % g)
643 raise error.Abort(_('guard %r too short') % g)
644 if g[0] not in '-+':
644 if g[0] not in '-+':
645 raise error.Abort(_('guard %r starts with invalid char') % g)
645 raise error.Abort(_('guard %r starts with invalid char') % g)
646 bad = self.checkguard(g[1:])
646 bad = self.checkguard(g[1:])
647 if bad:
647 if bad:
648 raise error.Abort(bad)
648 raise error.Abort(bad)
649 drop = self.guard_re.sub('', self.fullseries[idx])
649 drop = self.guard_re.sub('', self.fullseries[idx])
650 self.fullseries[idx] = drop + ''.join([' #' + g for g in guards])
650 self.fullseries[idx] = drop + ''.join([' #' + g for g in guards])
651 self.parseseries()
651 self.parseseries()
652 self.seriesdirty = True
652 self.seriesdirty = True
653
653
654 def pushable(self, idx):
654 def pushable(self, idx):
655 if isinstance(idx, bytes):
655 if isinstance(idx, bytes):
656 idx = self.series.index(idx)
656 idx = self.series.index(idx)
657 patchguards = self.seriesguards[idx]
657 patchguards = self.seriesguards[idx]
658 if not patchguards:
658 if not patchguards:
659 return True, None
659 return True, None
660 guards = self.active()
660 guards = self.active()
661 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
661 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
662 if exactneg:
662 if exactneg:
663 return False, repr(exactneg[0])
663 return False, repr(exactneg[0])
664 pos = [g for g in patchguards if g[0] == '+']
664 pos = [g for g in patchguards if g[0] == '+']
665 exactpos = [g for g in pos if g[1:] in guards]
665 exactpos = [g for g in pos if g[1:] in guards]
666 if pos:
666 if pos:
667 if exactpos:
667 if exactpos:
668 return True, repr(exactpos[0])
668 return True, repr(exactpos[0])
669 return False, ' '.join(map(repr, pos))
669 return False, ' '.join(map(repr, pos))
670 return True, ''
670 return True, ''
671
671
672 def explainpushable(self, idx, all_patches=False):
672 def explainpushable(self, idx, all_patches=False):
673 if all_patches:
673 if all_patches:
674 write = self.ui.write
674 write = self.ui.write
675 else:
675 else:
676 write = self.ui.warn
676 write = self.ui.warn
677
677
678 if all_patches or self.ui.verbose:
678 if all_patches or self.ui.verbose:
679 if isinstance(idx, str):
679 if isinstance(idx, str):
680 idx = self.series.index(idx)
680 idx = self.series.index(idx)
681 pushable, why = self.pushable(idx)
681 pushable, why = self.pushable(idx)
682 if all_patches and pushable:
682 if all_patches and pushable:
683 if why is None:
683 if why is None:
684 write(_('allowing %s - no guards in effect\n') %
684 write(_('allowing %s - no guards in effect\n') %
685 self.series[idx])
685 self.series[idx])
686 else:
686 else:
687 if not why:
687 if not why:
688 write(_('allowing %s - no matching negative guards\n') %
688 write(_('allowing %s - no matching negative guards\n') %
689 self.series[idx])
689 self.series[idx])
690 else:
690 else:
691 write(_('allowing %s - guarded by %s\n') %
691 write(_('allowing %s - guarded by %s\n') %
692 (self.series[idx], why))
692 (self.series[idx], why))
693 if not pushable:
693 if not pushable:
694 if why:
694 if why:
695 write(_('skipping %s - guarded by %s\n') %
695 write(_('skipping %s - guarded by %s\n') %
696 (self.series[idx], why))
696 (self.series[idx], why))
697 else:
697 else:
698 write(_('skipping %s - no matching guards\n') %
698 write(_('skipping %s - no matching guards\n') %
699 self.series[idx])
699 self.series[idx])
700
700
701 def savedirty(self):
701 def savedirty(self):
702 def writelist(items, path):
702 def writelist(items, path):
703 fp = self.opener(path, 'wb')
703 fp = self.opener(path, 'wb')
704 for i in items:
704 for i in items:
705 fp.write("%s\n" % i)
705 fp.write("%s\n" % i)
706 fp.close()
706 fp.close()
707 if self.applieddirty:
707 if self.applieddirty:
708 writelist(map(bytes, self.applied), self.statuspath)
708 writelist(map(bytes, self.applied), self.statuspath)
709 self.applieddirty = False
709 self.applieddirty = False
710 if self.seriesdirty:
710 if self.seriesdirty:
711 writelist(self.fullseries, self.seriespath)
711 writelist(self.fullseries, self.seriespath)
712 self.seriesdirty = False
712 self.seriesdirty = False
713 if self.guardsdirty:
713 if self.guardsdirty:
714 writelist(self.activeguards, self.guardspath)
714 writelist(self.activeguards, self.guardspath)
715 self.guardsdirty = False
715 self.guardsdirty = False
716 if self.added:
716 if self.added:
717 qrepo = self.qrepo()
717 qrepo = self.qrepo()
718 if qrepo:
718 if qrepo:
719 qrepo[None].add(f for f in self.added if f not in qrepo[None])
719 qrepo[None].add(f for f in self.added if f not in qrepo[None])
720 self.added = []
720 self.added = []
721
721
722 def removeundo(self, repo):
722 def removeundo(self, repo):
723 undo = repo.sjoin('undo')
723 undo = repo.sjoin('undo')
724 if not os.path.exists(undo):
724 if not os.path.exists(undo):
725 return
725 return
726 try:
726 try:
727 os.unlink(undo)
727 os.unlink(undo)
728 except OSError as inst:
728 except OSError as inst:
729 self.ui.warn(_('error removing undo: %s\n') %
729 self.ui.warn(_('error removing undo: %s\n') %
730 stringutil.forcebytestr(inst))
730 stringutil.forcebytestr(inst))
731
731
732 def backup(self, repo, files, copy=False):
732 def backup(self, repo, files, copy=False):
733 # backup local changes in --force case
733 # backup local changes in --force case
734 for f in sorted(files):
734 for f in sorted(files):
735 absf = repo.wjoin(f)
735 absf = repo.wjoin(f)
736 if os.path.lexists(absf):
736 if os.path.lexists(absf):
737 self.ui.note(_('saving current version of %s as %s\n') %
737 self.ui.note(_('saving current version of %s as %s\n') %
738 (f, scmutil.origpath(self.ui, repo, f)))
738 (f, scmutil.origpath(self.ui, repo, f)))
739
739
740 absorig = scmutil.origpath(self.ui, repo, absf)
740 absorig = scmutil.origpath(self.ui, repo, absf)
741 if copy:
741 if copy:
742 util.copyfile(absf, absorig)
742 util.copyfile(absf, absorig)
743 else:
743 else:
744 util.rename(absf, absorig)
744 util.rename(absf, absorig)
745
745
746 def printdiff(self, repo, diffopts, node1, node2=None, files=None,
746 def printdiff(self, repo, diffopts, node1, node2=None, files=None,
747 fp=None, changes=None, opts=None):
747 fp=None, changes=None, opts=None):
748 if opts is None:
748 if opts is None:
749 opts = {}
749 opts = {}
750 stat = opts.get('stat')
750 stat = opts.get('stat')
751 m = scmutil.match(repo[node1], files, opts)
751 m = scmutil.match(repo[node1], files, opts)
752 logcmdutil.diffordiffstat(self.ui, repo, diffopts, node1, node2, m,
752 logcmdutil.diffordiffstat(self.ui, repo, diffopts, node1, node2, m,
753 changes, stat, fp)
753 changes, stat, fp)
754
754
755 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
755 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
756 # first try just applying the patch
756 # first try just applying the patch
757 (err, n) = self.apply(repo, [patch], update_status=False,
757 (err, n) = self.apply(repo, [patch], update_status=False,
758 strict=True, merge=rev)
758 strict=True, merge=rev)
759
759
760 if err == 0:
760 if err == 0:
761 return (err, n)
761 return (err, n)
762
762
763 if n is None:
763 if n is None:
764 raise error.Abort(_("apply failed for patch %s") % patch)
764 raise error.Abort(_("apply failed for patch %s") % patch)
765
765
766 self.ui.warn(_("patch didn't work out, merging %s\n") % patch)
766 self.ui.warn(_("patch didn't work out, merging %s\n") % patch)
767
767
768 # apply failed, strip away that rev and merge.
768 # apply failed, strip away that rev and merge.
769 hg.clean(repo, head)
769 hg.clean(repo, head)
770 strip(self.ui, repo, [n], update=False, backup=False)
770 strip(self.ui, repo, [n], update=False, backup=False)
771
771
772 ctx = repo[rev]
772 ctx = repo[rev]
773 ret = hg.merge(repo, rev)
773 ret = hg.merge(repo, rev)
774 if ret:
774 if ret:
775 raise error.Abort(_("update returned %d") % ret)
775 raise error.Abort(_("update returned %d") % ret)
776 n = newcommit(repo, None, ctx.description(), ctx.user(), force=True)
776 n = newcommit(repo, None, ctx.description(), ctx.user(), force=True)
777 if n is None:
777 if n is None:
778 raise error.Abort(_("repo commit failed"))
778 raise error.Abort(_("repo commit failed"))
779 try:
779 try:
780 ph = patchheader(mergeq.join(patch), self.plainmode)
780 ph = patchheader(mergeq.join(patch), self.plainmode)
781 except Exception:
781 except Exception:
782 raise error.Abort(_("unable to read %s") % patch)
782 raise error.Abort(_("unable to read %s") % patch)
783
783
784 diffopts = self.patchopts(diffopts, patch)
784 diffopts = self.patchopts(diffopts, patch)
785 patchf = self.opener(patch, "w")
785 patchf = self.opener(patch, "w")
786 comments = bytes(ph)
786 comments = bytes(ph)
787 if comments:
787 if comments:
788 patchf.write(comments)
788 patchf.write(comments)
789 self.printdiff(repo, diffopts, head, n, fp=patchf)
789 self.printdiff(repo, diffopts, head, n, fp=patchf)
790 patchf.close()
790 patchf.close()
791 self.removeundo(repo)
791 self.removeundo(repo)
792 return (0, n)
792 return (0, n)
793
793
794 def qparents(self, repo, rev=None):
794 def qparents(self, repo, rev=None):
795 """return the mq handled parent or p1
795 """return the mq handled parent or p1
796
796
797 In some case where mq get himself in being the parent of a merge the
797 In some case where mq get himself in being the parent of a merge the
798 appropriate parent may be p2.
798 appropriate parent may be p2.
799 (eg: an in progress merge started with mq disabled)
799 (eg: an in progress merge started with mq disabled)
800
800
801 If no parent are managed by mq, p1 is returned.
801 If no parent are managed by mq, p1 is returned.
802 """
802 """
803 if rev is None:
803 if rev is None:
804 (p1, p2) = repo.dirstate.parents()
804 (p1, p2) = repo.dirstate.parents()
805 if p2 == nullid:
805 if p2 == nullid:
806 return p1
806 return p1
807 if not self.applied:
807 if not self.applied:
808 return None
808 return None
809 return self.applied[-1].node
809 return self.applied[-1].node
810 p1, p2 = repo.changelog.parents(rev)
810 p1, p2 = repo.changelog.parents(rev)
811 if p2 != nullid and p2 in [x.node for x in self.applied]:
811 if p2 != nullid and p2 in [x.node for x in self.applied]:
812 return p2
812 return p2
813 return p1
813 return p1
814
814
815 def mergepatch(self, repo, mergeq, series, diffopts):
815 def mergepatch(self, repo, mergeq, series, diffopts):
816 if not self.applied:
816 if not self.applied:
817 # each of the patches merged in will have two parents. This
817 # each of the patches merged in will have two parents. This
818 # can confuse the qrefresh, qdiff, and strip code because it
818 # can confuse the qrefresh, qdiff, and strip code because it
819 # needs to know which parent is actually in the patch queue.
819 # needs to know which parent is actually in the patch queue.
820 # so, we insert a merge marker with only one parent. This way
820 # so, we insert a merge marker with only one parent. This way
821 # the first patch in the queue is never a merge patch
821 # the first patch in the queue is never a merge patch
822 #
822 #
823 pname = ".hg.patches.merge.marker"
823 pname = ".hg.patches.merge.marker"
824 n = newcommit(repo, None, '[mq]: merge marker', force=True)
824 n = newcommit(repo, None, '[mq]: merge marker', force=True)
825 self.removeundo(repo)
825 self.removeundo(repo)
826 self.applied.append(statusentry(n, pname))
826 self.applied.append(statusentry(n, pname))
827 self.applieddirty = True
827 self.applieddirty = True
828
828
829 head = self.qparents(repo)
829 head = self.qparents(repo)
830
830
831 for patch in series:
831 for patch in series:
832 patch = mergeq.lookup(patch, strict=True)
832 patch = mergeq.lookup(patch, strict=True)
833 if not patch:
833 if not patch:
834 self.ui.warn(_("patch %s does not exist\n") % patch)
834 self.ui.warn(_("patch %s does not exist\n") % patch)
835 return (1, None)
835 return (1, None)
836 pushable, reason = self.pushable(patch)
836 pushable, reason = self.pushable(patch)
837 if not pushable:
837 if not pushable:
838 self.explainpushable(patch, all_patches=True)
838 self.explainpushable(patch, all_patches=True)
839 continue
839 continue
840 info = mergeq.isapplied(patch)
840 info = mergeq.isapplied(patch)
841 if not info:
841 if not info:
842 self.ui.warn(_("patch %s is not applied\n") % patch)
842 self.ui.warn(_("patch %s is not applied\n") % patch)
843 return (1, None)
843 return (1, None)
844 rev = info[1]
844 rev = info[1]
845 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
845 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
846 if head:
846 if head:
847 self.applied.append(statusentry(head, patch))
847 self.applied.append(statusentry(head, patch))
848 self.applieddirty = True
848 self.applieddirty = True
849 if err:
849 if err:
850 return (err, head)
850 return (err, head)
851 self.savedirty()
851 self.savedirty()
852 return (0, head)
852 return (0, head)
853
853
854 def patch(self, repo, patchfile):
854 def patch(self, repo, patchfile):
855 '''Apply patchfile to the working directory.
855 '''Apply patchfile to the working directory.
856 patchfile: name of patch file'''
856 patchfile: name of patch file'''
857 files = set()
857 files = set()
858 try:
858 try:
859 fuzz = patchmod.patch(self.ui, repo, patchfile, strip=1,
859 fuzz = patchmod.patch(self.ui, repo, patchfile, strip=1,
860 files=files, eolmode=None)
860 files=files, eolmode=None)
861 return (True, list(files), fuzz)
861 return (True, list(files), fuzz)
862 except Exception as inst:
862 except Exception as inst:
863 self.ui.note(stringutil.forcebytestr(inst) + '\n')
863 self.ui.note(stringutil.forcebytestr(inst) + '\n')
864 if not self.ui.verbose:
864 if not self.ui.verbose:
865 self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
865 self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
866 self.ui.traceback()
866 self.ui.traceback()
867 return (False, list(files), False)
867 return (False, list(files), False)
868
868
869 def apply(self, repo, series, list=False, update_status=True,
869 def apply(self, repo, series, list=False, update_status=True,
870 strict=False, patchdir=None, merge=None, all_files=None,
870 strict=False, patchdir=None, merge=None, all_files=None,
871 tobackup=None, keepchanges=False):
871 tobackup=None, keepchanges=False):
872 wlock = lock = tr = None
872 wlock = lock = tr = None
873 try:
873 try:
874 wlock = repo.wlock()
874 wlock = repo.wlock()
875 lock = repo.lock()
875 lock = repo.lock()
876 tr = repo.transaction("qpush")
876 tr = repo.transaction("qpush")
877 try:
877 try:
878 ret = self._apply(repo, series, list, update_status,
878 ret = self._apply(repo, series, list, update_status,
879 strict, patchdir, merge, all_files=all_files,
879 strict, patchdir, merge, all_files=all_files,
880 tobackup=tobackup, keepchanges=keepchanges)
880 tobackup=tobackup, keepchanges=keepchanges)
881 tr.close()
881 tr.close()
882 self.savedirty()
882 self.savedirty()
883 return ret
883 return ret
884 except AbortNoCleanup:
884 except AbortNoCleanup:
885 tr.close()
885 tr.close()
886 self.savedirty()
886 self.savedirty()
887 raise
887 raise
888 except: # re-raises
888 except: # re-raises
889 try:
889 try:
890 tr.abort()
890 tr.abort()
891 finally:
891 finally:
892 self.invalidate()
892 self.invalidate()
893 raise
893 raise
894 finally:
894 finally:
895 release(tr, lock, wlock)
895 release(tr, lock, wlock)
896 self.removeundo(repo)
896 self.removeundo(repo)
897
897
898 def _apply(self, repo, series, list=False, update_status=True,
898 def _apply(self, repo, series, list=False, update_status=True,
899 strict=False, patchdir=None, merge=None, all_files=None,
899 strict=False, patchdir=None, merge=None, all_files=None,
900 tobackup=None, keepchanges=False):
900 tobackup=None, keepchanges=False):
901 """returns (error, hash)
901 """returns (error, hash)
902
902
903 error = 1 for unable to read, 2 for patch failed, 3 for patch
903 error = 1 for unable to read, 2 for patch failed, 3 for patch
904 fuzz. tobackup is None or a set of files to backup before they
904 fuzz. tobackup is None or a set of files to backup before they
905 are modified by a patch.
905 are modified by a patch.
906 """
906 """
907 # TODO unify with commands.py
907 # TODO unify with commands.py
908 if not patchdir:
908 if not patchdir:
909 patchdir = self.path
909 patchdir = self.path
910 err = 0
910 err = 0
911 n = None
911 n = None
912 for patchname in series:
912 for patchname in series:
913 pushable, reason = self.pushable(patchname)
913 pushable, reason = self.pushable(patchname)
914 if not pushable:
914 if not pushable:
915 self.explainpushable(patchname, all_patches=True)
915 self.explainpushable(patchname, all_patches=True)
916 continue
916 continue
917 self.ui.status(_("applying %s\n") % patchname)
917 self.ui.status(_("applying %s\n") % patchname)
918 pf = os.path.join(patchdir, patchname)
918 pf = os.path.join(patchdir, patchname)
919
919
920 try:
920 try:
921 ph = patchheader(self.join(patchname), self.plainmode)
921 ph = patchheader(self.join(patchname), self.plainmode)
922 except IOError:
922 except IOError:
923 self.ui.warn(_("unable to read %s\n") % patchname)
923 self.ui.warn(_("unable to read %s\n") % patchname)
924 err = 1
924 err = 1
925 break
925 break
926
926
927 message = ph.message
927 message = ph.message
928 if not message:
928 if not message:
929 # The commit message should not be translated
929 # The commit message should not be translated
930 message = "imported patch %s\n" % patchname
930 message = "imported patch %s\n" % patchname
931 else:
931 else:
932 if list:
932 if list:
933 # The commit message should not be translated
933 # The commit message should not be translated
934 message.append("\nimported patch %s" % patchname)
934 message.append("\nimported patch %s" % patchname)
935 message = '\n'.join(message)
935 message = '\n'.join(message)
936
936
937 if ph.haspatch:
937 if ph.haspatch:
938 if tobackup:
938 if tobackup:
939 touched = patchmod.changedfiles(self.ui, repo, pf)
939 touched = patchmod.changedfiles(self.ui, repo, pf)
940 touched = set(touched) & tobackup
940 touched = set(touched) & tobackup
941 if touched and keepchanges:
941 if touched and keepchanges:
942 raise AbortNoCleanup(
942 raise AbortNoCleanup(
943 _("conflicting local changes found"),
943 _("conflicting local changes found"),
944 hint=_("did you forget to qrefresh?"))
944 hint=_("did you forget to qrefresh?"))
945 self.backup(repo, touched, copy=True)
945 self.backup(repo, touched, copy=True)
946 tobackup = tobackup - touched
946 tobackup = tobackup - touched
947 (patcherr, files, fuzz) = self.patch(repo, pf)
947 (patcherr, files, fuzz) = self.patch(repo, pf)
948 if all_files is not None:
948 if all_files is not None:
949 all_files.update(files)
949 all_files.update(files)
950 patcherr = not patcherr
950 patcherr = not patcherr
951 else:
951 else:
952 self.ui.warn(_("patch %s is empty\n") % patchname)
952 self.ui.warn(_("patch %s is empty\n") % patchname)
953 patcherr, files, fuzz = 0, [], 0
953 patcherr, files, fuzz = 0, [], 0
954
954
955 if merge and files:
955 if merge and files:
956 # Mark as removed/merged and update dirstate parent info
956 # Mark as removed/merged and update dirstate parent info
957 removed = []
957 removed = []
958 merged = []
958 merged = []
959 for f in files:
959 for f in files:
960 if os.path.lexists(repo.wjoin(f)):
960 if os.path.lexists(repo.wjoin(f)):
961 merged.append(f)
961 merged.append(f)
962 else:
962 else:
963 removed.append(f)
963 removed.append(f)
964 with repo.dirstate.parentchange():
964 with repo.dirstate.parentchange():
965 for f in removed:
965 for f in removed:
966 repo.dirstate.remove(f)
966 repo.dirstate.remove(f)
967 for f in merged:
967 for f in merged:
968 repo.dirstate.merge(f)
968 repo.dirstate.merge(f)
969 p1, p2 = repo.dirstate.parents()
969 p1, p2 = repo.dirstate.parents()
970 repo.setparents(p1, merge)
970 repo.setparents(p1, merge)
971
971
972 if all_files and '.hgsubstate' in all_files:
972 if all_files and '.hgsubstate' in all_files:
973 wctx = repo[None]
973 wctx = repo[None]
974 pctx = repo['.']
974 pctx = repo['.']
975 overwrite = False
975 overwrite = False
976 mergedsubstate = subrepoutil.submerge(repo, pctx, wctx, wctx,
976 mergedsubstate = subrepoutil.submerge(repo, pctx, wctx, wctx,
977 overwrite)
977 overwrite)
978 files += mergedsubstate.keys()
978 files += mergedsubstate.keys()
979
979
980 match = scmutil.matchfiles(repo, files or [])
980 match = scmutil.matchfiles(repo, files or [])
981 oldtip = repo['tip']
981 oldtip = repo['tip']
982 n = newcommit(repo, None, message, ph.user, ph.date, match=match,
982 n = newcommit(repo, None, message, ph.user, ph.date, match=match,
983 force=True)
983 force=True)
984 if repo['tip'] == oldtip:
984 if repo['tip'] == oldtip:
985 raise error.Abort(_("qpush exactly duplicates child changeset"))
985 raise error.Abort(_("qpush exactly duplicates child changeset"))
986 if n is None:
986 if n is None:
987 raise error.Abort(_("repository commit failed"))
987 raise error.Abort(_("repository commit failed"))
988
988
989 if update_status:
989 if update_status:
990 self.applied.append(statusentry(n, patchname))
990 self.applied.append(statusentry(n, patchname))
991
991
992 if patcherr:
992 if patcherr:
993 self.ui.warn(_("patch failed, rejects left in working "
993 self.ui.warn(_("patch failed, rejects left in working "
994 "directory\n"))
994 "directory\n"))
995 err = 2
995 err = 2
996 break
996 break
997
997
998 if fuzz and strict:
998 if fuzz and strict:
999 self.ui.warn(_("fuzz found when applying patch, stopping\n"))
999 self.ui.warn(_("fuzz found when applying patch, stopping\n"))
1000 err = 3
1000 err = 3
1001 break
1001 break
1002 return (err, n)
1002 return (err, n)
1003
1003
1004 def _cleanup(self, patches, numrevs, keep=False):
1004 def _cleanup(self, patches, numrevs, keep=False):
1005 if not keep:
1005 if not keep:
1006 r = self.qrepo()
1006 r = self.qrepo()
1007 if r:
1007 if r:
1008 r[None].forget(patches)
1008 r[None].forget(patches)
1009 for p in patches:
1009 for p in patches:
1010 try:
1010 try:
1011 os.unlink(self.join(p))
1011 os.unlink(self.join(p))
1012 except OSError as inst:
1012 except OSError as inst:
1013 if inst.errno != errno.ENOENT:
1013 if inst.errno != errno.ENOENT:
1014 raise
1014 raise
1015
1015
1016 qfinished = []
1016 qfinished = []
1017 if numrevs:
1017 if numrevs:
1018 qfinished = self.applied[:numrevs]
1018 qfinished = self.applied[:numrevs]
1019 del self.applied[:numrevs]
1019 del self.applied[:numrevs]
1020 self.applieddirty = True
1020 self.applieddirty = True
1021
1021
1022 unknown = []
1022 unknown = []
1023
1023
1024 for (i, p) in sorted([(self.findseries(p), p) for p in patches],
1024 for (i, p) in sorted([(self.findseries(p), p) for p in patches],
1025 reverse=True):
1025 reverse=True):
1026 if i is not None:
1026 if i is not None:
1027 del self.fullseries[i]
1027 del self.fullseries[i]
1028 else:
1028 else:
1029 unknown.append(p)
1029 unknown.append(p)
1030
1030
1031 if unknown:
1031 if unknown:
1032 if numrevs:
1032 if numrevs:
1033 rev = dict((entry.name, entry.node) for entry in qfinished)
1033 rev = dict((entry.name, entry.node) for entry in qfinished)
1034 for p in unknown:
1034 for p in unknown:
1035 msg = _('revision %s refers to unknown patches: %s\n')
1035 msg = _('revision %s refers to unknown patches: %s\n')
1036 self.ui.warn(msg % (short(rev[p]), p))
1036 self.ui.warn(msg % (short(rev[p]), p))
1037 else:
1037 else:
1038 msg = _('unknown patches: %s\n')
1038 msg = _('unknown patches: %s\n')
1039 raise error.Abort(''.join(msg % p for p in unknown))
1039 raise error.Abort(''.join(msg % p for p in unknown))
1040
1040
1041 self.parseseries()
1041 self.parseseries()
1042 self.seriesdirty = True
1042 self.seriesdirty = True
1043 return [entry.node for entry in qfinished]
1043 return [entry.node for entry in qfinished]
1044
1044
1045 def _revpatches(self, repo, revs):
1045 def _revpatches(self, repo, revs):
1046 firstrev = repo[self.applied[0].node].rev()
1046 firstrev = repo[self.applied[0].node].rev()
1047 patches = []
1047 patches = []
1048 for i, rev in enumerate(revs):
1048 for i, rev in enumerate(revs):
1049
1049
1050 if rev < firstrev:
1050 if rev < firstrev:
1051 raise error.Abort(_('revision %d is not managed') % rev)
1051 raise error.Abort(_('revision %d is not managed') % rev)
1052
1052
1053 ctx = repo[rev]
1053 ctx = repo[rev]
1054 base = self.applied[i].node
1054 base = self.applied[i].node
1055 if ctx.node() != base:
1055 if ctx.node() != base:
1056 msg = _('cannot delete revision %d above applied patches')
1056 msg = _('cannot delete revision %d above applied patches')
1057 raise error.Abort(msg % rev)
1057 raise error.Abort(msg % rev)
1058
1058
1059 patch = self.applied[i].name
1059 patch = self.applied[i].name
1060 for fmt in ('[mq]: %s', 'imported patch %s'):
1060 for fmt in ('[mq]: %s', 'imported patch %s'):
1061 if ctx.description() == fmt % patch:
1061 if ctx.description() == fmt % patch:
1062 msg = _('patch %s finalized without changeset message\n')
1062 msg = _('patch %s finalized without changeset message\n')
1063 repo.ui.status(msg % patch)
1063 repo.ui.status(msg % patch)
1064 break
1064 break
1065
1065
1066 patches.append(patch)
1066 patches.append(patch)
1067 return patches
1067 return patches
1068
1068
1069 def finish(self, repo, revs):
1069 def finish(self, repo, revs):
1070 # Manually trigger phase computation to ensure phasedefaults is
1070 # Manually trigger phase computation to ensure phasedefaults is
1071 # executed before we remove the patches.
1071 # executed before we remove the patches.
1072 repo._phasecache
1072 repo._phasecache
1073 patches = self._revpatches(repo, sorted(revs))
1073 patches = self._revpatches(repo, sorted(revs))
1074 qfinished = self._cleanup(patches, len(patches))
1074 qfinished = self._cleanup(patches, len(patches))
1075 if qfinished and repo.ui.configbool('mq', 'secret'):
1075 if qfinished and repo.ui.configbool('mq', 'secret'):
1076 # only use this logic when the secret option is added
1076 # only use this logic when the secret option is added
1077 oldqbase = repo[qfinished[0]]
1077 oldqbase = repo[qfinished[0]]
1078 tphase = phases.newcommitphase(repo.ui)
1078 tphase = phases.newcommitphase(repo.ui)
1079 if oldqbase.phase() > tphase and oldqbase.p1().phase() <= tphase:
1079 if oldqbase.phase() > tphase and oldqbase.p1().phase() <= tphase:
1080 with repo.transaction('qfinish') as tr:
1080 with repo.transaction('qfinish') as tr:
1081 phases.advanceboundary(repo, tr, tphase, qfinished)
1081 phases.advanceboundary(repo, tr, tphase, qfinished)
1082
1082
1083 def delete(self, repo, patches, opts):
1083 def delete(self, repo, patches, opts):
1084 if not patches and not opts.get('rev'):
1084 if not patches and not opts.get('rev'):
1085 raise error.Abort(_('qdelete requires at least one revision or '
1085 raise error.Abort(_('qdelete requires at least one revision or '
1086 'patch name'))
1086 'patch name'))
1087
1087
1088 realpatches = []
1088 realpatches = []
1089 for patch in patches:
1089 for patch in patches:
1090 patch = self.lookup(patch, strict=True)
1090 patch = self.lookup(patch, strict=True)
1091 info = self.isapplied(patch)
1091 info = self.isapplied(patch)
1092 if info:
1092 if info:
1093 raise error.Abort(_("cannot delete applied patch %s") % patch)
1093 raise error.Abort(_("cannot delete applied patch %s") % patch)
1094 if patch not in self.series:
1094 if patch not in self.series:
1095 raise error.Abort(_("patch %s not in series file") % patch)
1095 raise error.Abort(_("patch %s not in series file") % patch)
1096 if patch not in realpatches:
1096 if patch not in realpatches:
1097 realpatches.append(patch)
1097 realpatches.append(patch)
1098
1098
1099 numrevs = 0
1099 numrevs = 0
1100 if opts.get('rev'):
1100 if opts.get('rev'):
1101 if not self.applied:
1101 if not self.applied:
1102 raise error.Abort(_('no patches applied'))
1102 raise error.Abort(_('no patches applied'))
1103 revs = scmutil.revrange(repo, opts.get('rev'))
1103 revs = scmutil.revrange(repo, opts.get('rev'))
1104 revs.sort()
1104 revs.sort()
1105 revpatches = self._revpatches(repo, revs)
1105 revpatches = self._revpatches(repo, revs)
1106 realpatches += revpatches
1106 realpatches += revpatches
1107 numrevs = len(revpatches)
1107 numrevs = len(revpatches)
1108
1108
1109 self._cleanup(realpatches, numrevs, opts.get('keep'))
1109 self._cleanup(realpatches, numrevs, opts.get('keep'))
1110
1110
1111 def checktoppatch(self, repo):
1111 def checktoppatch(self, repo):
1112 '''check that working directory is at qtip'''
1112 '''check that working directory is at qtip'''
1113 if self.applied:
1113 if self.applied:
1114 top = self.applied[-1].node
1114 top = self.applied[-1].node
1115 patch = self.applied[-1].name
1115 patch = self.applied[-1].name
1116 if repo.dirstate.p1() != top:
1116 if repo.dirstate.p1() != top:
1117 raise error.Abort(_("working directory revision is not qtip"))
1117 raise error.Abort(_("working directory revision is not qtip"))
1118 return top, patch
1118 return top, patch
1119 return None, None
1119 return None, None
1120
1120
1121 def putsubstate2changes(self, substatestate, changes):
1121 def putsubstate2changes(self, substatestate, changes):
1122 for files in changes[:3]:
1122 for files in changes[:3]:
1123 if '.hgsubstate' in files:
1123 if '.hgsubstate' in files:
1124 return # already listed up
1124 return # already listed up
1125 # not yet listed up
1125 # not yet listed up
1126 if substatestate in 'a?':
1126 if substatestate in 'a?':
1127 changes[1].append('.hgsubstate')
1127 changes[1].append('.hgsubstate')
1128 elif substatestate in 'r':
1128 elif substatestate in 'r':
1129 changes[2].append('.hgsubstate')
1129 changes[2].append('.hgsubstate')
1130 else: # modified
1130 else: # modified
1131 changes[0].append('.hgsubstate')
1131 changes[0].append('.hgsubstate')
1132
1132
1133 def checklocalchanges(self, repo, force=False, refresh=True):
1133 def checklocalchanges(self, repo, force=False, refresh=True):
1134 excsuffix = ''
1134 excsuffix = ''
1135 if refresh:
1135 if refresh:
1136 excsuffix = ', qrefresh first'
1136 excsuffix = ', qrefresh first'
1137 # plain versions for i18n tool to detect them
1137 # plain versions for i18n tool to detect them
1138 _("local changes found, qrefresh first")
1138 _("local changes found, qrefresh first")
1139 _("local changed subrepos found, qrefresh first")
1139 _("local changed subrepos found, qrefresh first")
1140 return checklocalchanges(repo, force, excsuffix)
1140 return checklocalchanges(repo, force, excsuffix)
1141
1141
1142 _reserved = ('series', 'status', 'guards', '.', '..')
1142 _reserved = ('series', 'status', 'guards', '.', '..')
1143 def checkreservedname(self, name):
1143 def checkreservedname(self, name):
1144 if name in self._reserved:
1144 if name in self._reserved:
1145 raise error.Abort(_('"%s" cannot be used as the name of a patch')
1145 raise error.Abort(_('"%s" cannot be used as the name of a patch')
1146 % name)
1146 % name)
1147 if name != name.strip():
1147 if name != name.strip():
1148 # whitespace is stripped by parseseries()
1148 # whitespace is stripped by parseseries()
1149 raise error.Abort(_('patch name cannot begin or end with '
1149 raise error.Abort(_('patch name cannot begin or end with '
1150 'whitespace'))
1150 'whitespace'))
1151 for prefix in ('.hg', '.mq'):
1151 for prefix in ('.hg', '.mq'):
1152 if name.startswith(prefix):
1152 if name.startswith(prefix):
1153 raise error.Abort(_('patch name cannot begin with "%s"')
1153 raise error.Abort(_('patch name cannot begin with "%s"')
1154 % prefix)
1154 % prefix)
1155 for c in ('#', ':', '\r', '\n'):
1155 for c in ('#', ':', '\r', '\n'):
1156 if c in name:
1156 if c in name:
1157 raise error.Abort(_('%r cannot be used in the name of a patch')
1157 raise error.Abort(_('%r cannot be used in the name of a patch')
1158 % c)
1158 % c)
1159
1159
1160 def checkpatchname(self, name, force=False):
1160 def checkpatchname(self, name, force=False):
1161 self.checkreservedname(name)
1161 self.checkreservedname(name)
1162 if not force and os.path.exists(self.join(name)):
1162 if not force and os.path.exists(self.join(name)):
1163 if os.path.isdir(self.join(name)):
1163 if os.path.isdir(self.join(name)):
1164 raise error.Abort(_('"%s" already exists as a directory')
1164 raise error.Abort(_('"%s" already exists as a directory')
1165 % name)
1165 % name)
1166 else:
1166 else:
1167 raise error.Abort(_('patch "%s" already exists') % name)
1167 raise error.Abort(_('patch "%s" already exists') % name)
1168
1168
1169 def makepatchname(self, title, fallbackname):
1169 def makepatchname(self, title, fallbackname):
1170 """Return a suitable filename for title, adding a suffix to make
1170 """Return a suitable filename for title, adding a suffix to make
1171 it unique in the existing list"""
1171 it unique in the existing list"""
1172 namebase = re.sub('[\s\W_]+', '_', title.lower()).strip('_')
1172 namebase = re.sub('[\s\W_]+', '_', title.lower()).strip('_')
1173 namebase = namebase[:75] # avoid too long name (issue5117)
1173 namebase = namebase[:75] # avoid too long name (issue5117)
1174 if namebase:
1174 if namebase:
1175 try:
1175 try:
1176 self.checkreservedname(namebase)
1176 self.checkreservedname(namebase)
1177 except error.Abort:
1177 except error.Abort:
1178 namebase = fallbackname
1178 namebase = fallbackname
1179 else:
1179 else:
1180 namebase = fallbackname
1180 namebase = fallbackname
1181 name = namebase
1181 name = namebase
1182 i = 0
1182 i = 0
1183 while True:
1183 while True:
1184 if name not in self.fullseries:
1184 if name not in self.fullseries:
1185 try:
1185 try:
1186 self.checkpatchname(name)
1186 self.checkpatchname(name)
1187 break
1187 break
1188 except error.Abort:
1188 except error.Abort:
1189 pass
1189 pass
1190 i += 1
1190 i += 1
1191 name = '%s__%d' % (namebase, i)
1191 name = '%s__%d' % (namebase, i)
1192 return name
1192 return name
1193
1193
1194 def checkkeepchanges(self, keepchanges, force):
1194 def checkkeepchanges(self, keepchanges, force):
1195 if force and keepchanges:
1195 if force and keepchanges:
1196 raise error.Abort(_('cannot use both --force and --keep-changes'))
1196 raise error.Abort(_('cannot use both --force and --keep-changes'))
1197
1197
1198 def new(self, repo, patchfn, *pats, **opts):
1198 def new(self, repo, patchfn, *pats, **opts):
1199 """options:
1199 """options:
1200 msg: a string or a no-argument function returning a string
1200 msg: a string or a no-argument function returning a string
1201 """
1201 """
1202 opts = pycompat.byteskwargs(opts)
1202 opts = pycompat.byteskwargs(opts)
1203 msg = opts.get('msg')
1203 msg = opts.get('msg')
1204 edit = opts.get('edit')
1204 edit = opts.get('edit')
1205 editform = opts.get('editform', 'mq.qnew')
1205 editform = opts.get('editform', 'mq.qnew')
1206 user = opts.get('user')
1206 user = opts.get('user')
1207 date = opts.get('date')
1207 date = opts.get('date')
1208 if date:
1208 if date:
1209 date = dateutil.parsedate(date)
1209 date = dateutil.parsedate(date)
1210 diffopts = self.diffopts({'git': opts.get('git')}, plain=True)
1210 diffopts = self.diffopts({'git': opts.get('git')}, plain=True)
1211 if opts.get('checkname', True):
1211 if opts.get('checkname', True):
1212 self.checkpatchname(patchfn)
1212 self.checkpatchname(patchfn)
1213 inclsubs = checksubstate(repo)
1213 inclsubs = checksubstate(repo)
1214 if inclsubs:
1214 if inclsubs:
1215 substatestate = repo.dirstate['.hgsubstate']
1215 substatestate = repo.dirstate['.hgsubstate']
1216 if opts.get('include') or opts.get('exclude') or pats:
1216 if opts.get('include') or opts.get('exclude') or pats:
1217 # detect missing files in pats
1217 # detect missing files in pats
1218 def badfn(f, msg):
1218 def badfn(f, msg):
1219 if f != '.hgsubstate': # .hgsubstate is auto-created
1219 if f != '.hgsubstate': # .hgsubstate is auto-created
1220 raise error.Abort('%s: %s' % (f, msg))
1220 raise error.Abort('%s: %s' % (f, msg))
1221 match = scmutil.match(repo[None], pats, opts, badfn=badfn)
1221 match = scmutil.match(repo[None], pats, opts, badfn=badfn)
1222 changes = repo.status(match=match)
1222 changes = repo.status(match=match)
1223 else:
1223 else:
1224 changes = self.checklocalchanges(repo, force=True)
1224 changes = self.checklocalchanges(repo, force=True)
1225 commitfiles = list(inclsubs)
1225 commitfiles = list(inclsubs)
1226 for files in changes[:3]:
1226 for files in changes[:3]:
1227 commitfiles.extend(files)
1227 commitfiles.extend(files)
1228 match = scmutil.matchfiles(repo, commitfiles)
1228 match = scmutil.matchfiles(repo, commitfiles)
1229 if len(repo[None].parents()) > 1:
1229 if len(repo[None].parents()) > 1:
1230 raise error.Abort(_('cannot manage merge changesets'))
1230 raise error.Abort(_('cannot manage merge changesets'))
1231 self.checktoppatch(repo)
1231 self.checktoppatch(repo)
1232 insert = self.fullseriesend()
1232 insert = self.fullseriesend()
1233 with repo.wlock():
1233 with repo.wlock():
1234 try:
1234 try:
1235 # if patch file write fails, abort early
1235 # if patch file write fails, abort early
1236 p = self.opener(patchfn, "w")
1236 p = self.opener(patchfn, "w")
1237 except IOError as e:
1237 except IOError as e:
1238 raise error.Abort(_('cannot write patch "%s": %s')
1238 raise error.Abort(_('cannot write patch "%s": %s')
1239 % (patchfn, encoding.strtolocal(e.strerror)))
1239 % (patchfn, encoding.strtolocal(e.strerror)))
1240 try:
1240 try:
1241 defaultmsg = "[mq]: %s" % patchfn
1241 defaultmsg = "[mq]: %s" % patchfn
1242 editor = cmdutil.getcommiteditor(editform=editform)
1242 editor = cmdutil.getcommiteditor(editform=editform)
1243 if edit:
1243 if edit:
1244 def finishdesc(desc):
1244 def finishdesc(desc):
1245 if desc.rstrip():
1245 if desc.rstrip():
1246 return desc
1246 return desc
1247 else:
1247 else:
1248 return defaultmsg
1248 return defaultmsg
1249 # i18n: this message is shown in editor with "HG: " prefix
1249 # i18n: this message is shown in editor with "HG: " prefix
1250 extramsg = _('Leave message empty to use default message.')
1250 extramsg = _('Leave message empty to use default message.')
1251 editor = cmdutil.getcommiteditor(finishdesc=finishdesc,
1251 editor = cmdutil.getcommiteditor(finishdesc=finishdesc,
1252 extramsg=extramsg,
1252 extramsg=extramsg,
1253 editform=editform)
1253 editform=editform)
1254 commitmsg = msg
1254 commitmsg = msg
1255 else:
1255 else:
1256 commitmsg = msg or defaultmsg
1256 commitmsg = msg or defaultmsg
1257
1257
1258 n = newcommit(repo, None, commitmsg, user, date, match=match,
1258 n = newcommit(repo, None, commitmsg, user, date, match=match,
1259 force=True, editor=editor)
1259 force=True, editor=editor)
1260 if n is None:
1260 if n is None:
1261 raise error.Abort(_("repo commit failed"))
1261 raise error.Abort(_("repo commit failed"))
1262 try:
1262 try:
1263 self.fullseries[insert:insert] = [patchfn]
1263 self.fullseries[insert:insert] = [patchfn]
1264 self.applied.append(statusentry(n, patchfn))
1264 self.applied.append(statusentry(n, patchfn))
1265 self.parseseries()
1265 self.parseseries()
1266 self.seriesdirty = True
1266 self.seriesdirty = True
1267 self.applieddirty = True
1267 self.applieddirty = True
1268 nctx = repo[n]
1268 nctx = repo[n]
1269 ph = patchheader(self.join(patchfn), self.plainmode)
1269 ph = patchheader(self.join(patchfn), self.plainmode)
1270 if user:
1270 if user:
1271 ph.setuser(user)
1271 ph.setuser(user)
1272 if date:
1272 if date:
1273 ph.setdate('%d %d' % date)
1273 ph.setdate('%d %d' % date)
1274 ph.setparent(hex(nctx.p1().node()))
1274 ph.setparent(hex(nctx.p1().node()))
1275 msg = nctx.description().strip()
1275 msg = nctx.description().strip()
1276 if msg == defaultmsg.strip():
1276 if msg == defaultmsg.strip():
1277 msg = ''
1277 msg = ''
1278 ph.setmessage(msg)
1278 ph.setmessage(msg)
1279 p.write(bytes(ph))
1279 p.write(bytes(ph))
1280 if commitfiles:
1280 if commitfiles:
1281 parent = self.qparents(repo, n)
1281 parent = self.qparents(repo, n)
1282 if inclsubs:
1282 if inclsubs:
1283 self.putsubstate2changes(substatestate, changes)
1283 self.putsubstate2changes(substatestate, changes)
1284 chunks = patchmod.diff(repo, node1=parent, node2=n,
1284 chunks = patchmod.diff(repo, node1=parent, node2=n,
1285 changes=changes, opts=diffopts)
1285 changes=changes, opts=diffopts)
1286 for chunk in chunks:
1286 for chunk in chunks:
1287 p.write(chunk)
1287 p.write(chunk)
1288 p.close()
1288 p.close()
1289 r = self.qrepo()
1289 r = self.qrepo()
1290 if r:
1290 if r:
1291 r[None].add([patchfn])
1291 r[None].add([patchfn])
1292 except: # re-raises
1292 except: # re-raises
1293 repo.rollback()
1293 repo.rollback()
1294 raise
1294 raise
1295 except Exception:
1295 except Exception:
1296 patchpath = self.join(patchfn)
1296 patchpath = self.join(patchfn)
1297 try:
1297 try:
1298 os.unlink(patchpath)
1298 os.unlink(patchpath)
1299 except OSError:
1299 except OSError:
1300 self.ui.warn(_('error unlinking %s\n') % patchpath)
1300 self.ui.warn(_('error unlinking %s\n') % patchpath)
1301 raise
1301 raise
1302 self.removeundo(repo)
1302 self.removeundo(repo)
1303
1303
1304 def isapplied(self, patch):
1304 def isapplied(self, patch):
1305 """returns (index, rev, patch)"""
1305 """returns (index, rev, patch)"""
1306 for i, a in enumerate(self.applied):
1306 for i, a in enumerate(self.applied):
1307 if a.name == patch:
1307 if a.name == patch:
1308 return (i, a.node, a.name)
1308 return (i, a.node, a.name)
1309 return None
1309 return None
1310
1310
1311 # if the exact patch name does not exist, we try a few
1311 # if the exact patch name does not exist, we try a few
1312 # variations. If strict is passed, we try only #1
1312 # variations. If strict is passed, we try only #1
1313 #
1313 #
1314 # 1) a number (as string) to indicate an offset in the series file
1314 # 1) a number (as string) to indicate an offset in the series file
1315 # 2) a unique substring of the patch name was given
1315 # 2) a unique substring of the patch name was given
1316 # 3) patchname[-+]num to indicate an offset in the series file
1316 # 3) patchname[-+]num to indicate an offset in the series file
1317 def lookup(self, patch, strict=False):
1317 def lookup(self, patch, strict=False):
1318 def partialname(s):
1318 def partialname(s):
1319 if s in self.series:
1319 if s in self.series:
1320 return s
1320 return s
1321 matches = [x for x in self.series if s in x]
1321 matches = [x for x in self.series if s in x]
1322 if len(matches) > 1:
1322 if len(matches) > 1:
1323 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
1323 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
1324 for m in matches:
1324 for m in matches:
1325 self.ui.warn(' %s\n' % m)
1325 self.ui.warn(' %s\n' % m)
1326 return None
1326 return None
1327 if matches:
1327 if matches:
1328 return matches[0]
1328 return matches[0]
1329 if self.series and self.applied:
1329 if self.series and self.applied:
1330 if s == 'qtip':
1330 if s == 'qtip':
1331 return self.series[self.seriesend(True) - 1]
1331 return self.series[self.seriesend(True) - 1]
1332 if s == 'qbase':
1332 if s == 'qbase':
1333 return self.series[0]
1333 return self.series[0]
1334 return None
1334 return None
1335
1335
1336 if patch in self.series:
1336 if patch in self.series:
1337 return patch
1337 return patch
1338
1338
1339 if not os.path.isfile(self.join(patch)):
1339 if not os.path.isfile(self.join(patch)):
1340 try:
1340 try:
1341 sno = int(patch)
1341 sno = int(patch)
1342 except (ValueError, OverflowError):
1342 except (ValueError, OverflowError):
1343 pass
1343 pass
1344 else:
1344 else:
1345 if -len(self.series) <= sno < len(self.series):
1345 if -len(self.series) <= sno < len(self.series):
1346 return self.series[sno]
1346 return self.series[sno]
1347
1347
1348 if not strict:
1348 if not strict:
1349 res = partialname(patch)
1349 res = partialname(patch)
1350 if res:
1350 if res:
1351 return res
1351 return res
1352 minus = patch.rfind('-')
1352 minus = patch.rfind('-')
1353 if minus >= 0:
1353 if minus >= 0:
1354 res = partialname(patch[:minus])
1354 res = partialname(patch[:minus])
1355 if res:
1355 if res:
1356 i = self.series.index(res)
1356 i = self.series.index(res)
1357 try:
1357 try:
1358 off = int(patch[minus + 1:] or 1)
1358 off = int(patch[minus + 1:] or 1)
1359 except (ValueError, OverflowError):
1359 except (ValueError, OverflowError):
1360 pass
1360 pass
1361 else:
1361 else:
1362 if i - off >= 0:
1362 if i - off >= 0:
1363 return self.series[i - off]
1363 return self.series[i - off]
1364 plus = patch.rfind('+')
1364 plus = patch.rfind('+')
1365 if plus >= 0:
1365 if plus >= 0:
1366 res = partialname(patch[:plus])
1366 res = partialname(patch[:plus])
1367 if res:
1367 if res:
1368 i = self.series.index(res)
1368 i = self.series.index(res)
1369 try:
1369 try:
1370 off = int(patch[plus + 1:] or 1)
1370 off = int(patch[plus + 1:] or 1)
1371 except (ValueError, OverflowError):
1371 except (ValueError, OverflowError):
1372 pass
1372 pass
1373 else:
1373 else:
1374 if i + off < len(self.series):
1374 if i + off < len(self.series):
1375 return self.series[i + off]
1375 return self.series[i + off]
1376 raise error.Abort(_("patch %s not in series") % patch)
1376 raise error.Abort(_("patch %s not in series") % patch)
1377
1377
1378 def push(self, repo, patch=None, force=False, list=False, mergeq=None,
1378 def push(self, repo, patch=None, force=False, list=False, mergeq=None,
1379 all=False, move=False, exact=False, nobackup=False,
1379 all=False, move=False, exact=False, nobackup=False,
1380 keepchanges=False):
1380 keepchanges=False):
1381 self.checkkeepchanges(keepchanges, force)
1381 self.checkkeepchanges(keepchanges, force)
1382 diffopts = self.diffopts()
1382 diffopts = self.diffopts()
1383 with repo.wlock():
1383 with repo.wlock():
1384 heads = []
1384 heads = []
1385 for hs in repo.branchmap().itervalues():
1385 for hs in repo.branchmap().itervalues():
1386 heads.extend(hs)
1386 heads.extend(hs)
1387 if not heads:
1387 if not heads:
1388 heads = [nullid]
1388 heads = [nullid]
1389 if repo.dirstate.p1() not in heads and not exact:
1389 if repo.dirstate.p1() not in heads and not exact:
1390 self.ui.status(_("(working directory not at a head)\n"))
1390 self.ui.status(_("(working directory not at a head)\n"))
1391
1391
1392 if not self.series:
1392 if not self.series:
1393 self.ui.warn(_('no patches in series\n'))
1393 self.ui.warn(_('no patches in series\n'))
1394 return 0
1394 return 0
1395
1395
1396 # Suppose our series file is: A B C and the current 'top'
1396 # Suppose our series file is: A B C and the current 'top'
1397 # patch is B. qpush C should be performed (moving forward)
1397 # patch is B. qpush C should be performed (moving forward)
1398 # qpush B is a NOP (no change) qpush A is an error (can't
1398 # qpush B is a NOP (no change) qpush A is an error (can't
1399 # go backwards with qpush)
1399 # go backwards with qpush)
1400 if patch:
1400 if patch:
1401 patch = self.lookup(patch)
1401 patch = self.lookup(patch)
1402 info = self.isapplied(patch)
1402 info = self.isapplied(patch)
1403 if info and info[0] >= len(self.applied) - 1:
1403 if info and info[0] >= len(self.applied) - 1:
1404 self.ui.warn(
1404 self.ui.warn(
1405 _('qpush: %s is already at the top\n') % patch)
1405 _('qpush: %s is already at the top\n') % patch)
1406 return 0
1406 return 0
1407
1407
1408 pushable, reason = self.pushable(patch)
1408 pushable, reason = self.pushable(patch)
1409 if pushable:
1409 if pushable:
1410 if self.series.index(patch) < self.seriesend():
1410 if self.series.index(patch) < self.seriesend():
1411 raise error.Abort(
1411 raise error.Abort(
1412 _("cannot push to a previous patch: %s") % patch)
1412 _("cannot push to a previous patch: %s") % patch)
1413 else:
1413 else:
1414 if reason:
1414 if reason:
1415 reason = _('guarded by %s') % reason
1415 reason = _('guarded by %s') % reason
1416 else:
1416 else:
1417 reason = _('no matching guards')
1417 reason = _('no matching guards')
1418 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1418 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1419 return 1
1419 return 1
1420 elif all:
1420 elif all:
1421 patch = self.series[-1]
1421 patch = self.series[-1]
1422 if self.isapplied(patch):
1422 if self.isapplied(patch):
1423 self.ui.warn(_('all patches are currently applied\n'))
1423 self.ui.warn(_('all patches are currently applied\n'))
1424 return 0
1424 return 0
1425
1425
1426 # Following the above example, starting at 'top' of B:
1426 # Following the above example, starting at 'top' of B:
1427 # qpush should be performed (pushes C), but a subsequent
1427 # qpush should be performed (pushes C), but a subsequent
1428 # qpush without an argument is an error (nothing to
1428 # qpush without an argument is an error (nothing to
1429 # apply). This allows a loop of "...while hg qpush..." to
1429 # apply). This allows a loop of "...while hg qpush..." to
1430 # work as it detects an error when done
1430 # work as it detects an error when done
1431 start = self.seriesend()
1431 start = self.seriesend()
1432 if start == len(self.series):
1432 if start == len(self.series):
1433 self.ui.warn(_('patch series already fully applied\n'))
1433 self.ui.warn(_('patch series already fully applied\n'))
1434 return 1
1434 return 1
1435 if not force and not keepchanges:
1435 if not force and not keepchanges:
1436 self.checklocalchanges(repo, refresh=self.applied)
1436 self.checklocalchanges(repo, refresh=self.applied)
1437
1437
1438 if exact:
1438 if exact:
1439 if keepchanges:
1439 if keepchanges:
1440 raise error.Abort(
1440 raise error.Abort(
1441 _("cannot use --exact and --keep-changes together"))
1441 _("cannot use --exact and --keep-changes together"))
1442 if move:
1442 if move:
1443 raise error.Abort(_('cannot use --exact and --move '
1443 raise error.Abort(_('cannot use --exact and --move '
1444 'together'))
1444 'together'))
1445 if self.applied:
1445 if self.applied:
1446 raise error.Abort(_('cannot push --exact with applied '
1446 raise error.Abort(_('cannot push --exact with applied '
1447 'patches'))
1447 'patches'))
1448 root = self.series[start]
1448 root = self.series[start]
1449 target = patchheader(self.join(root), self.plainmode).parent
1449 target = patchheader(self.join(root), self.plainmode).parent
1450 if not target:
1450 if not target:
1451 raise error.Abort(
1451 raise error.Abort(
1452 _("%s does not have a parent recorded") % root)
1452 _("%s does not have a parent recorded") % root)
1453 if not repo[target] == repo['.']:
1453 if not repo[target] == repo['.']:
1454 hg.update(repo, target)
1454 hg.update(repo, target)
1455
1455
1456 if move:
1456 if move:
1457 if not patch:
1457 if not patch:
1458 raise error.Abort(_("please specify the patch to move"))
1458 raise error.Abort(_("please specify the patch to move"))
1459 for fullstart, rpn in enumerate(self.fullseries):
1459 for fullstart, rpn in enumerate(self.fullseries):
1460 # strip markers for patch guards
1460 # strip markers for patch guards
1461 if self.guard_re.split(rpn, 1)[0] == self.series[start]:
1461 if self.guard_re.split(rpn, 1)[0] == self.series[start]:
1462 break
1462 break
1463 for i, rpn in enumerate(self.fullseries[fullstart:]):
1463 for i, rpn in enumerate(self.fullseries[fullstart:]):
1464 # strip markers for patch guards
1464 # strip markers for patch guards
1465 if self.guard_re.split(rpn, 1)[0] == patch:
1465 if self.guard_re.split(rpn, 1)[0] == patch:
1466 break
1466 break
1467 index = fullstart + i
1467 index = fullstart + i
1468 assert index < len(self.fullseries)
1468 assert index < len(self.fullseries)
1469 fullpatch = self.fullseries[index]
1469 fullpatch = self.fullseries[index]
1470 del self.fullseries[index]
1470 del self.fullseries[index]
1471 self.fullseries.insert(fullstart, fullpatch)
1471 self.fullseries.insert(fullstart, fullpatch)
1472 self.parseseries()
1472 self.parseseries()
1473 self.seriesdirty = True
1473 self.seriesdirty = True
1474
1474
1475 self.applieddirty = True
1475 self.applieddirty = True
1476 if start > 0:
1476 if start > 0:
1477 self.checktoppatch(repo)
1477 self.checktoppatch(repo)
1478 if not patch:
1478 if not patch:
1479 patch = self.series[start]
1479 patch = self.series[start]
1480 end = start + 1
1480 end = start + 1
1481 else:
1481 else:
1482 end = self.series.index(patch, start) + 1
1482 end = self.series.index(patch, start) + 1
1483
1483
1484 tobackup = set()
1484 tobackup = set()
1485 if (not nobackup and force) or keepchanges:
1485 if (not nobackup and force) or keepchanges:
1486 status = self.checklocalchanges(repo, force=True)
1486 status = self.checklocalchanges(repo, force=True)
1487 if keepchanges:
1487 if keepchanges:
1488 tobackup.update(status.modified + status.added +
1488 tobackup.update(status.modified + status.added +
1489 status.removed + status.deleted)
1489 status.removed + status.deleted)
1490 else:
1490 else:
1491 tobackup.update(status.modified + status.added)
1491 tobackup.update(status.modified + status.added)
1492
1492
1493 s = self.series[start:end]
1493 s = self.series[start:end]
1494 all_files = set()
1494 all_files = set()
1495 try:
1495 try:
1496 if mergeq:
1496 if mergeq:
1497 ret = self.mergepatch(repo, mergeq, s, diffopts)
1497 ret = self.mergepatch(repo, mergeq, s, diffopts)
1498 else:
1498 else:
1499 ret = self.apply(repo, s, list, all_files=all_files,
1499 ret = self.apply(repo, s, list, all_files=all_files,
1500 tobackup=tobackup, keepchanges=keepchanges)
1500 tobackup=tobackup, keepchanges=keepchanges)
1501 except AbortNoCleanup:
1501 except AbortNoCleanup:
1502 raise
1502 raise
1503 except: # re-raises
1503 except: # re-raises
1504 self.ui.warn(_('cleaning up working directory...\n'))
1504 self.ui.warn(_('cleaning up working directory...\n'))
1505 cmdutil.revert(self.ui, repo, repo['.'],
1505 cmdutil.revert(self.ui, repo, repo['.'],
1506 repo.dirstate.parents(), no_backup=True)
1506 repo.dirstate.parents(), no_backup=True)
1507 # only remove unknown files that we know we touched or
1507 # only remove unknown files that we know we touched or
1508 # created while patching
1508 # created while patching
1509 for f in all_files:
1509 for f in all_files:
1510 if f not in repo.dirstate:
1510 if f not in repo.dirstate:
1511 repo.wvfs.unlinkpath(f, ignoremissing=True)
1511 repo.wvfs.unlinkpath(f, ignoremissing=True)
1512 self.ui.warn(_('done\n'))
1512 self.ui.warn(_('done\n'))
1513 raise
1513 raise
1514
1514
1515 if not self.applied:
1515 if not self.applied:
1516 return ret[0]
1516 return ret[0]
1517 top = self.applied[-1].name
1517 top = self.applied[-1].name
1518 if ret[0] and ret[0] > 1:
1518 if ret[0] and ret[0] > 1:
1519 msg = _("errors during apply, please fix and qrefresh %s\n")
1519 msg = _("errors during apply, please fix and qrefresh %s\n")
1520 self.ui.write(msg % top)
1520 self.ui.write(msg % top)
1521 else:
1521 else:
1522 self.ui.write(_("now at: %s\n") % top)
1522 self.ui.write(_("now at: %s\n") % top)
1523 return ret[0]
1523 return ret[0]
1524
1524
1525 def pop(self, repo, patch=None, force=False, update=True, all=False,
1525 def pop(self, repo, patch=None, force=False, update=True, all=False,
1526 nobackup=False, keepchanges=False):
1526 nobackup=False, keepchanges=False):
1527 self.checkkeepchanges(keepchanges, force)
1527 self.checkkeepchanges(keepchanges, force)
1528 with repo.wlock():
1528 with repo.wlock():
1529 if patch:
1529 if patch:
1530 # index, rev, patch
1530 # index, rev, patch
1531 info = self.isapplied(patch)
1531 info = self.isapplied(patch)
1532 if not info:
1532 if not info:
1533 patch = self.lookup(patch)
1533 patch = self.lookup(patch)
1534 info = self.isapplied(patch)
1534 info = self.isapplied(patch)
1535 if not info:
1535 if not info:
1536 raise error.Abort(_("patch %s is not applied") % patch)
1536 raise error.Abort(_("patch %s is not applied") % patch)
1537
1537
1538 if not self.applied:
1538 if not self.applied:
1539 # Allow qpop -a to work repeatedly,
1539 # Allow qpop -a to work repeatedly,
1540 # but not qpop without an argument
1540 # but not qpop without an argument
1541 self.ui.warn(_("no patches applied\n"))
1541 self.ui.warn(_("no patches applied\n"))
1542 return not all
1542 return not all
1543
1543
1544 if all:
1544 if all:
1545 start = 0
1545 start = 0
1546 elif patch:
1546 elif patch:
1547 start = info[0] + 1
1547 start = info[0] + 1
1548 else:
1548 else:
1549 start = len(self.applied) - 1
1549 start = len(self.applied) - 1
1550
1550
1551 if start >= len(self.applied):
1551 if start >= len(self.applied):
1552 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
1552 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
1553 return
1553 return
1554
1554
1555 if not update:
1555 if not update:
1556 parents = repo.dirstate.parents()
1556 parents = repo.dirstate.parents()
1557 rr = [x.node for x in self.applied]
1557 rr = [x.node for x in self.applied]
1558 for p in parents:
1558 for p in parents:
1559 if p in rr:
1559 if p in rr:
1560 self.ui.warn(_("qpop: forcing dirstate update\n"))
1560 self.ui.warn(_("qpop: forcing dirstate update\n"))
1561 update = True
1561 update = True
1562 else:
1562 else:
1563 parents = [p.node() for p in repo[None].parents()]
1563 parents = [p.node() for p in repo[None].parents()]
1564 update = any(entry.node in parents
1564 update = any(entry.node in parents
1565 for entry in self.applied[start:])
1565 for entry in self.applied[start:])
1566
1566
1567 tobackup = set()
1567 tobackup = set()
1568 if update:
1568 if update:
1569 s = self.checklocalchanges(repo, force=force or keepchanges)
1569 s = self.checklocalchanges(repo, force=force or keepchanges)
1570 if force:
1570 if force:
1571 if not nobackup:
1571 if not nobackup:
1572 tobackup.update(s.modified + s.added)
1572 tobackup.update(s.modified + s.added)
1573 elif keepchanges:
1573 elif keepchanges:
1574 tobackup.update(s.modified + s.added +
1574 tobackup.update(s.modified + s.added +
1575 s.removed + s.deleted)
1575 s.removed + s.deleted)
1576
1576
1577 self.applieddirty = True
1577 self.applieddirty = True
1578 end = len(self.applied)
1578 end = len(self.applied)
1579 rev = self.applied[start].node
1579 rev = self.applied[start].node
1580
1580
1581 try:
1581 try:
1582 heads = repo.changelog.heads(rev)
1582 heads = repo.changelog.heads(rev)
1583 except error.LookupError:
1583 except error.LookupError:
1584 node = short(rev)
1584 node = short(rev)
1585 raise error.Abort(_('trying to pop unknown node %s') % node)
1585 raise error.Abort(_('trying to pop unknown node %s') % node)
1586
1586
1587 if heads != [self.applied[-1].node]:
1587 if heads != [self.applied[-1].node]:
1588 raise error.Abort(_("popping would remove a revision not "
1588 raise error.Abort(_("popping would remove a revision not "
1589 "managed by this patch queue"))
1589 "managed by this patch queue"))
1590 if not repo[self.applied[-1].node].mutable():
1590 if not repo[self.applied[-1].node].mutable():
1591 raise error.Abort(
1591 raise error.Abort(
1592 _("popping would remove a public revision"),
1592 _("popping would remove a public revision"),
1593 hint=_("see 'hg help phases' for details"))
1593 hint=_("see 'hg help phases' for details"))
1594
1594
1595 # we know there are no local changes, so we can make a simplified
1595 # we know there are no local changes, so we can make a simplified
1596 # form of hg.update.
1596 # form of hg.update.
1597 if update:
1597 if update:
1598 qp = self.qparents(repo, rev)
1598 qp = self.qparents(repo, rev)
1599 ctx = repo[qp]
1599 ctx = repo[qp]
1600 m, a, r, d = repo.status(qp, '.')[:4]
1600 m, a, r, d = repo.status(qp, '.')[:4]
1601 if d:
1601 if d:
1602 raise error.Abort(_("deletions found between repo revs"))
1602 raise error.Abort(_("deletions found between repo revs"))
1603
1603
1604 tobackup = set(a + m + r) & tobackup
1604 tobackup = set(a + m + r) & tobackup
1605 if keepchanges and tobackup:
1605 if keepchanges and tobackup:
1606 raise error.Abort(_("local changes found, qrefresh first"))
1606 raise error.Abort(_("local changes found, qrefresh first"))
1607 self.backup(repo, tobackup)
1607 self.backup(repo, tobackup)
1608 with repo.dirstate.parentchange():
1608 with repo.dirstate.parentchange():
1609 for f in a:
1609 for f in a:
1610 repo.wvfs.unlinkpath(f, ignoremissing=True)
1610 repo.wvfs.unlinkpath(f, ignoremissing=True)
1611 repo.dirstate.drop(f)
1611 repo.dirstate.drop(f)
1612 for f in m + r:
1612 for f in m + r:
1613 fctx = ctx[f]
1613 fctx = ctx[f]
1614 repo.wwrite(f, fctx.data(), fctx.flags())
1614 repo.wwrite(f, fctx.data(), fctx.flags())
1615 repo.dirstate.normal(f)
1615 repo.dirstate.normal(f)
1616 repo.setparents(qp, nullid)
1616 repo.setparents(qp, nullid)
1617 for patch in reversed(self.applied[start:end]):
1617 for patch in reversed(self.applied[start:end]):
1618 self.ui.status(_("popping %s\n") % patch.name)
1618 self.ui.status(_("popping %s\n") % patch.name)
1619 del self.applied[start:end]
1619 del self.applied[start:end]
1620 strip(self.ui, repo, [rev], update=False, backup=False)
1620 strip(self.ui, repo, [rev], update=False, backup=False)
1621 for s, state in repo['.'].substate.items():
1621 for s, state in repo['.'].substate.items():
1622 repo['.'].sub(s).get(state)
1622 repo['.'].sub(s).get(state)
1623 if self.applied:
1623 if self.applied:
1624 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1624 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1625 else:
1625 else:
1626 self.ui.write(_("patch queue now empty\n"))
1626 self.ui.write(_("patch queue now empty\n"))
1627
1627
1628 def diff(self, repo, pats, opts):
1628 def diff(self, repo, pats, opts):
1629 top, patch = self.checktoppatch(repo)
1629 top, patch = self.checktoppatch(repo)
1630 if not top:
1630 if not top:
1631 self.ui.write(_("no patches applied\n"))
1631 self.ui.write(_("no patches applied\n"))
1632 return
1632 return
1633 qp = self.qparents(repo, top)
1633 qp = self.qparents(repo, top)
1634 if opts.get('reverse'):
1634 if opts.get('reverse'):
1635 node1, node2 = None, qp
1635 node1, node2 = None, qp
1636 else:
1636 else:
1637 node1, node2 = qp, None
1637 node1, node2 = qp, None
1638 diffopts = self.diffopts(opts, patch)
1638 diffopts = self.diffopts(opts, patch)
1639 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1639 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1640
1640
1641 def refresh(self, repo, pats=None, **opts):
1641 def refresh(self, repo, pats=None, **opts):
1642 opts = pycompat.byteskwargs(opts)
1642 opts = pycompat.byteskwargs(opts)
1643 if not self.applied:
1643 if not self.applied:
1644 self.ui.write(_("no patches applied\n"))
1644 self.ui.write(_("no patches applied\n"))
1645 return 1
1645 return 1
1646 msg = opts.get('msg', '').rstrip()
1646 msg = opts.get('msg', '').rstrip()
1647 edit = opts.get('edit')
1647 edit = opts.get('edit')
1648 editform = opts.get('editform', 'mq.qrefresh')
1648 editform = opts.get('editform', 'mq.qrefresh')
1649 newuser = opts.get('user')
1649 newuser = opts.get('user')
1650 newdate = opts.get('date')
1650 newdate = opts.get('date')
1651 if newdate:
1651 if newdate:
1652 newdate = '%d %d' % dateutil.parsedate(newdate)
1652 newdate = '%d %d' % dateutil.parsedate(newdate)
1653 wlock = repo.wlock()
1653 wlock = repo.wlock()
1654
1654
1655 try:
1655 try:
1656 self.checktoppatch(repo)
1656 self.checktoppatch(repo)
1657 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1657 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1658 if repo.changelog.heads(top) != [top]:
1658 if repo.changelog.heads(top) != [top]:
1659 raise error.Abort(_("cannot qrefresh a revision with children"))
1659 raise error.Abort(_("cannot qrefresh a revision with children"))
1660 if not repo[top].mutable():
1660 if not repo[top].mutable():
1661 raise error.Abort(_("cannot qrefresh public revision"),
1661 raise error.Abort(_("cannot qrefresh public revision"),
1662 hint=_("see 'hg help phases' for details"))
1662 hint=_("see 'hg help phases' for details"))
1663
1663
1664 cparents = repo.changelog.parents(top)
1664 cparents = repo.changelog.parents(top)
1665 patchparent = self.qparents(repo, top)
1665 patchparent = self.qparents(repo, top)
1666
1666
1667 inclsubs = checksubstate(repo, hex(patchparent))
1667 inclsubs = checksubstate(repo, hex(patchparent))
1668 if inclsubs:
1668 if inclsubs:
1669 substatestate = repo.dirstate['.hgsubstate']
1669 substatestate = repo.dirstate['.hgsubstate']
1670
1670
1671 ph = patchheader(self.join(patchfn), self.plainmode)
1671 ph = patchheader(self.join(patchfn), self.plainmode)
1672 diffopts = self.diffopts({'git': opts.get('git')}, patchfn,
1672 diffopts = self.diffopts({'git': opts.get('git')}, patchfn,
1673 plain=True)
1673 plain=True)
1674 if newuser:
1674 if newuser:
1675 ph.setuser(newuser)
1675 ph.setuser(newuser)
1676 if newdate:
1676 if newdate:
1677 ph.setdate(newdate)
1677 ph.setdate(newdate)
1678 ph.setparent(hex(patchparent))
1678 ph.setparent(hex(patchparent))
1679
1679
1680 # only commit new patch when write is complete
1680 # only commit new patch when write is complete
1681 patchf = self.opener(patchfn, 'w', atomictemp=True)
1681 patchf = self.opener(patchfn, 'w', atomictemp=True)
1682
1682
1683 # update the dirstate in place, strip off the qtip commit
1683 # update the dirstate in place, strip off the qtip commit
1684 # and then commit.
1684 # and then commit.
1685 #
1685 #
1686 # this should really read:
1686 # this should really read:
1687 # mm, dd, aa = repo.status(top, patchparent)[:3]
1687 # mm, dd, aa = repo.status(top, patchparent)[:3]
1688 # but we do it backwards to take advantage of manifest/changelog
1688 # but we do it backwards to take advantage of manifest/changelog
1689 # caching against the next repo.status call
1689 # caching against the next repo.status call
1690 mm, aa, dd = repo.status(patchparent, top)[:3]
1690 mm, aa, dd = repo.status(patchparent, top)[:3]
1691 changes = repo.changelog.read(top)
1691 changes = repo.changelog.read(top)
1692 man = repo.manifestlog[changes[0]].read()
1692 man = repo.manifestlog[changes[0]].read()
1693 aaa = aa[:]
1693 aaa = aa[:]
1694 match1 = scmutil.match(repo[None], pats, opts)
1694 match1 = scmutil.match(repo[None], pats, opts)
1695 # in short mode, we only diff the files included in the
1695 # in short mode, we only diff the files included in the
1696 # patch already plus specified files
1696 # patch already plus specified files
1697 if opts.get('short'):
1697 if opts.get('short'):
1698 # if amending a patch, we start with existing
1698 # if amending a patch, we start with existing
1699 # files plus specified files - unfiltered
1699 # files plus specified files - unfiltered
1700 match = scmutil.matchfiles(repo, mm + aa + dd + match1.files())
1700 match = scmutil.matchfiles(repo, mm + aa + dd + match1.files())
1701 # filter with include/exclude options
1701 # filter with include/exclude options
1702 match1 = scmutil.match(repo[None], opts=opts)
1702 match1 = scmutil.match(repo[None], opts=opts)
1703 else:
1703 else:
1704 match = scmutil.matchall(repo)
1704 match = scmutil.matchall(repo)
1705 m, a, r, d = repo.status(match=match)[:4]
1705 m, a, r, d = repo.status(match=match)[:4]
1706 mm = set(mm)
1706 mm = set(mm)
1707 aa = set(aa)
1707 aa = set(aa)
1708 dd = set(dd)
1708 dd = set(dd)
1709
1709
1710 # we might end up with files that were added between
1710 # we might end up with files that were added between
1711 # qtip and the dirstate parent, but then changed in the
1711 # qtip and the dirstate parent, but then changed in the
1712 # local dirstate. in this case, we want them to only
1712 # local dirstate. in this case, we want them to only
1713 # show up in the added section
1713 # show up in the added section
1714 for x in m:
1714 for x in m:
1715 if x not in aa:
1715 if x not in aa:
1716 mm.add(x)
1716 mm.add(x)
1717 # we might end up with files added by the local dirstate that
1717 # we might end up with files added by the local dirstate that
1718 # were deleted by the patch. In this case, they should only
1718 # were deleted by the patch. In this case, they should only
1719 # show up in the changed section.
1719 # show up in the changed section.
1720 for x in a:
1720 for x in a:
1721 if x in dd:
1721 if x in dd:
1722 dd.remove(x)
1722 dd.remove(x)
1723 mm.add(x)
1723 mm.add(x)
1724 else:
1724 else:
1725 aa.add(x)
1725 aa.add(x)
1726 # make sure any files deleted in the local dirstate
1726 # make sure any files deleted in the local dirstate
1727 # are not in the add or change column of the patch
1727 # are not in the add or change column of the patch
1728 forget = []
1728 forget = []
1729 for x in d + r:
1729 for x in d + r:
1730 if x in aa:
1730 if x in aa:
1731 aa.remove(x)
1731 aa.remove(x)
1732 forget.append(x)
1732 forget.append(x)
1733 continue
1733 continue
1734 else:
1734 else:
1735 mm.discard(x)
1735 mm.discard(x)
1736 dd.add(x)
1736 dd.add(x)
1737
1737
1738 m = list(mm)
1738 m = list(mm)
1739 r = list(dd)
1739 r = list(dd)
1740 a = list(aa)
1740 a = list(aa)
1741
1741
1742 # create 'match' that includes the files to be recommitted.
1742 # create 'match' that includes the files to be recommitted.
1743 # apply match1 via repo.status to ensure correct case handling.
1743 # apply match1 via repo.status to ensure correct case handling.
1744 cm, ca, cr, cd = repo.status(patchparent, match=match1)[:4]
1744 cm, ca, cr, cd = repo.status(patchparent, match=match1)[:4]
1745 allmatches = set(cm + ca + cr + cd)
1745 allmatches = set(cm + ca + cr + cd)
1746 refreshchanges = [x.intersection(allmatches) for x in (mm, aa, dd)]
1746 refreshchanges = [x.intersection(allmatches) for x in (mm, aa, dd)]
1747
1747
1748 files = set(inclsubs)
1748 files = set(inclsubs)
1749 for x in refreshchanges:
1749 for x in refreshchanges:
1750 files.update(x)
1750 files.update(x)
1751 match = scmutil.matchfiles(repo, files)
1751 match = scmutil.matchfiles(repo, files)
1752
1752
1753 bmlist = repo[top].bookmarks()
1753 bmlist = repo[top].bookmarks()
1754
1754
1755 dsguard = None
1755 dsguard = None
1756 try:
1756 try:
1757 dsguard = dirstateguard.dirstateguard(repo, 'mq.refresh')
1757 dsguard = dirstateguard.dirstateguard(repo, 'mq.refresh')
1758 if diffopts.git or diffopts.upgrade:
1758 if diffopts.git or diffopts.upgrade:
1759 copies = {}
1759 copies = {}
1760 for dst in a:
1760 for dst in a:
1761 src = repo.dirstate.copied(dst)
1761 src = repo.dirstate.copied(dst)
1762 # during qfold, the source file for copies may
1762 # during qfold, the source file for copies may
1763 # be removed. Treat this as a simple add.
1763 # be removed. Treat this as a simple add.
1764 if src is not None and src in repo.dirstate:
1764 if src is not None and src in repo.dirstate:
1765 copies.setdefault(src, []).append(dst)
1765 copies.setdefault(src, []).append(dst)
1766 repo.dirstate.add(dst)
1766 repo.dirstate.add(dst)
1767 # remember the copies between patchparent and qtip
1767 # remember the copies between patchparent and qtip
1768 for dst in aaa:
1768 for dst in aaa:
1769 f = repo.file(dst)
1769 f = repo.file(dst)
1770 src = f.renamed(man[dst])
1770 src = f.renamed(man[dst])
1771 if src:
1771 if src:
1772 copies.setdefault(src[0], []).extend(
1772 copies.setdefault(src[0], []).extend(
1773 copies.get(dst, []))
1773 copies.get(dst, []))
1774 if dst in a:
1774 if dst in a:
1775 copies[src[0]].append(dst)
1775 copies[src[0]].append(dst)
1776 # we can't copy a file created by the patch itself
1776 # we can't copy a file created by the patch itself
1777 if dst in copies:
1777 if dst in copies:
1778 del copies[dst]
1778 del copies[dst]
1779 for src, dsts in copies.iteritems():
1779 for src, dsts in copies.iteritems():
1780 for dst in dsts:
1780 for dst in dsts:
1781 repo.dirstate.copy(src, dst)
1781 repo.dirstate.copy(src, dst)
1782 else:
1782 else:
1783 for dst in a:
1783 for dst in a:
1784 repo.dirstate.add(dst)
1784 repo.dirstate.add(dst)
1785 # Drop useless copy information
1785 # Drop useless copy information
1786 for f in list(repo.dirstate.copies()):
1786 for f in list(repo.dirstate.copies()):
1787 repo.dirstate.copy(None, f)
1787 repo.dirstate.copy(None, f)
1788 for f in r:
1788 for f in r:
1789 repo.dirstate.remove(f)
1789 repo.dirstate.remove(f)
1790 # if the patch excludes a modified file, mark that
1790 # if the patch excludes a modified file, mark that
1791 # file with mtime=0 so status can see it.
1791 # file with mtime=0 so status can see it.
1792 mm = []
1792 mm = []
1793 for i in xrange(len(m) - 1, -1, -1):
1793 for i in xrange(len(m) - 1, -1, -1):
1794 if not match1(m[i]):
1794 if not match1(m[i]):
1795 mm.append(m[i])
1795 mm.append(m[i])
1796 del m[i]
1796 del m[i]
1797 for f in m:
1797 for f in m:
1798 repo.dirstate.normal(f)
1798 repo.dirstate.normal(f)
1799 for f in mm:
1799 for f in mm:
1800 repo.dirstate.normallookup(f)
1800 repo.dirstate.normallookup(f)
1801 for f in forget:
1801 for f in forget:
1802 repo.dirstate.drop(f)
1802 repo.dirstate.drop(f)
1803
1803
1804 user = ph.user or changes[1]
1804 user = ph.user or changes[1]
1805
1805
1806 oldphase = repo[top].phase()
1806 oldphase = repo[top].phase()
1807
1807
1808 # assumes strip can roll itself back if interrupted
1808 # assumes strip can roll itself back if interrupted
1809 repo.setparents(*cparents)
1809 repo.setparents(*cparents)
1810 self.applied.pop()
1810 self.applied.pop()
1811 self.applieddirty = True
1811 self.applieddirty = True
1812 strip(self.ui, repo, [top], update=False, backup=False)
1812 strip(self.ui, repo, [top], update=False, backup=False)
1813 dsguard.close()
1813 dsguard.close()
1814 finally:
1814 finally:
1815 release(dsguard)
1815 release(dsguard)
1816
1816
1817 try:
1817 try:
1818 # might be nice to attempt to roll back strip after this
1818 # might be nice to attempt to roll back strip after this
1819
1819
1820 defaultmsg = "[mq]: %s" % patchfn
1820 defaultmsg = "[mq]: %s" % patchfn
1821 editor = cmdutil.getcommiteditor(editform=editform)
1821 editor = cmdutil.getcommiteditor(editform=editform)
1822 if edit:
1822 if edit:
1823 def finishdesc(desc):
1823 def finishdesc(desc):
1824 if desc.rstrip():
1824 if desc.rstrip():
1825 ph.setmessage(desc)
1825 ph.setmessage(desc)
1826 return desc
1826 return desc
1827 return defaultmsg
1827 return defaultmsg
1828 # i18n: this message is shown in editor with "HG: " prefix
1828 # i18n: this message is shown in editor with "HG: " prefix
1829 extramsg = _('Leave message empty to use default message.')
1829 extramsg = _('Leave message empty to use default message.')
1830 editor = cmdutil.getcommiteditor(finishdesc=finishdesc,
1830 editor = cmdutil.getcommiteditor(finishdesc=finishdesc,
1831 extramsg=extramsg,
1831 extramsg=extramsg,
1832 editform=editform)
1832 editform=editform)
1833 message = msg or "\n".join(ph.message)
1833 message = msg or "\n".join(ph.message)
1834 elif not msg:
1834 elif not msg:
1835 if not ph.message:
1835 if not ph.message:
1836 message = defaultmsg
1836 message = defaultmsg
1837 else:
1837 else:
1838 message = "\n".join(ph.message)
1838 message = "\n".join(ph.message)
1839 else:
1839 else:
1840 message = msg
1840 message = msg
1841 ph.setmessage(msg)
1841 ph.setmessage(msg)
1842
1842
1843 # Ensure we create a new changeset in the same phase than
1843 # Ensure we create a new changeset in the same phase than
1844 # the old one.
1844 # the old one.
1845 lock = tr = None
1845 lock = tr = None
1846 try:
1846 try:
1847 lock = repo.lock()
1847 lock = repo.lock()
1848 tr = repo.transaction('mq')
1848 tr = repo.transaction('mq')
1849 n = newcommit(repo, oldphase, message, user, ph.date,
1849 n = newcommit(repo, oldphase, message, user, ph.date,
1850 match=match, force=True, editor=editor)
1850 match=match, force=True, editor=editor)
1851 # only write patch after a successful commit
1851 # only write patch after a successful commit
1852 c = [list(x) for x in refreshchanges]
1852 c = [list(x) for x in refreshchanges]
1853 if inclsubs:
1853 if inclsubs:
1854 self.putsubstate2changes(substatestate, c)
1854 self.putsubstate2changes(substatestate, c)
1855 chunks = patchmod.diff(repo, patchparent,
1855 chunks = patchmod.diff(repo, patchparent,
1856 changes=c, opts=diffopts)
1856 changes=c, opts=diffopts)
1857 comments = bytes(ph)
1857 comments = bytes(ph)
1858 if comments:
1858 if comments:
1859 patchf.write(comments)
1859 patchf.write(comments)
1860 for chunk in chunks:
1860 for chunk in chunks:
1861 patchf.write(chunk)
1861 patchf.write(chunk)
1862 patchf.close()
1862 patchf.close()
1863
1863
1864 marks = repo._bookmarks
1864 marks = repo._bookmarks
1865 marks.applychanges(repo, tr, [(bm, n) for bm in bmlist])
1865 marks.applychanges(repo, tr, [(bm, n) for bm in bmlist])
1866 tr.close()
1866 tr.close()
1867
1867
1868 self.applied.append(statusentry(n, patchfn))
1868 self.applied.append(statusentry(n, patchfn))
1869 finally:
1869 finally:
1870 lockmod.release(tr, lock)
1870 lockmod.release(tr, lock)
1871 except: # re-raises
1871 except: # re-raises
1872 ctx = repo[cparents[0]]
1872 ctx = repo[cparents[0]]
1873 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1873 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1874 self.savedirty()
1874 self.savedirty()
1875 self.ui.warn(_('qrefresh interrupted while patch was popped! '
1875 self.ui.warn(_('qrefresh interrupted while patch was popped! '
1876 '(revert --all, qpush to recover)\n'))
1876 '(revert --all, qpush to recover)\n'))
1877 raise
1877 raise
1878 finally:
1878 finally:
1879 wlock.release()
1879 wlock.release()
1880 self.removeundo(repo)
1880 self.removeundo(repo)
1881
1881
1882 def init(self, repo, create=False):
1882 def init(self, repo, create=False):
1883 if not create and os.path.isdir(self.path):
1883 if not create and os.path.isdir(self.path):
1884 raise error.Abort(_("patch queue directory already exists"))
1884 raise error.Abort(_("patch queue directory already exists"))
1885 try:
1885 try:
1886 os.mkdir(self.path)
1886 os.mkdir(self.path)
1887 except OSError as inst:
1887 except OSError as inst:
1888 if inst.errno != errno.EEXIST or not create:
1888 if inst.errno != errno.EEXIST or not create:
1889 raise
1889 raise
1890 if create:
1890 if create:
1891 return self.qrepo(create=True)
1891 return self.qrepo(create=True)
1892
1892
1893 def unapplied(self, repo, patch=None):
1893 def unapplied(self, repo, patch=None):
1894 if patch and patch not in self.series:
1894 if patch and patch not in self.series:
1895 raise error.Abort(_("patch %s is not in series file") % patch)
1895 raise error.Abort(_("patch %s is not in series file") % patch)
1896 if not patch:
1896 if not patch:
1897 start = self.seriesend()
1897 start = self.seriesend()
1898 else:
1898 else:
1899 start = self.series.index(patch) + 1
1899 start = self.series.index(patch) + 1
1900 unapplied = []
1900 unapplied = []
1901 for i in xrange(start, len(self.series)):
1901 for i in xrange(start, len(self.series)):
1902 pushable, reason = self.pushable(i)
1902 pushable, reason = self.pushable(i)
1903 if pushable:
1903 if pushable:
1904 unapplied.append((i, self.series[i]))
1904 unapplied.append((i, self.series[i]))
1905 self.explainpushable(i)
1905 self.explainpushable(i)
1906 return unapplied
1906 return unapplied
1907
1907
1908 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1908 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1909 summary=False):
1909 summary=False):
1910 def displayname(pfx, patchname, state):
1910 def displayname(pfx, patchname, state):
1911 if pfx:
1911 if pfx:
1912 self.ui.write(pfx)
1912 self.ui.write(pfx)
1913 if summary:
1913 if summary:
1914 ph = patchheader(self.join(patchname), self.plainmode)
1914 ph = patchheader(self.join(patchname), self.plainmode)
1915 if ph.message:
1915 if ph.message:
1916 msg = ph.message[0]
1916 msg = ph.message[0]
1917 else:
1917 else:
1918 msg = ''
1918 msg = ''
1919
1919
1920 if self.ui.formatted():
1920 if self.ui.formatted():
1921 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
1921 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
1922 if width > 0:
1922 if width > 0:
1923 msg = stringutil.ellipsis(msg, width)
1923 msg = stringutil.ellipsis(msg, width)
1924 else:
1924 else:
1925 msg = ''
1925 msg = ''
1926 self.ui.write(patchname, label='qseries.' + state)
1926 self.ui.write(patchname, label='qseries.' + state)
1927 self.ui.write(': ')
1927 self.ui.write(': ')
1928 self.ui.write(msg, label='qseries.message.' + state)
1928 self.ui.write(msg, label='qseries.message.' + state)
1929 else:
1929 else:
1930 self.ui.write(patchname, label='qseries.' + state)
1930 self.ui.write(patchname, label='qseries.' + state)
1931 self.ui.write('\n')
1931 self.ui.write('\n')
1932
1932
1933 applied = set([p.name for p in self.applied])
1933 applied = set([p.name for p in self.applied])
1934 if length is None:
1934 if length is None:
1935 length = len(self.series) - start
1935 length = len(self.series) - start
1936 if not missing:
1936 if not missing:
1937 if self.ui.verbose:
1937 if self.ui.verbose:
1938 idxwidth = len("%d" % (start + length - 1))
1938 idxwidth = len("%d" % (start + length - 1))
1939 for i in xrange(start, start + length):
1939 for i in xrange(start, start + length):
1940 patch = self.series[i]
1940 patch = self.series[i]
1941 if patch in applied:
1941 if patch in applied:
1942 char, state = 'A', 'applied'
1942 char, state = 'A', 'applied'
1943 elif self.pushable(i)[0]:
1943 elif self.pushable(i)[0]:
1944 char, state = 'U', 'unapplied'
1944 char, state = 'U', 'unapplied'
1945 else:
1945 else:
1946 char, state = 'G', 'guarded'
1946 char, state = 'G', 'guarded'
1947 pfx = ''
1947 pfx = ''
1948 if self.ui.verbose:
1948 if self.ui.verbose:
1949 pfx = '%*d %s ' % (idxwidth, i, char)
1949 pfx = '%*d %s ' % (idxwidth, i, char)
1950 elif status and status != char:
1950 elif status and status != char:
1951 continue
1951 continue
1952 displayname(pfx, patch, state)
1952 displayname(pfx, patch, state)
1953 else:
1953 else:
1954 msng_list = []
1954 msng_list = []
1955 for root, dirs, files in os.walk(self.path):
1955 for root, dirs, files in os.walk(self.path):
1956 d = root[len(self.path) + 1:]
1956 d = root[len(self.path) + 1:]
1957 for f in files:
1957 for f in files:
1958 fl = os.path.join(d, f)
1958 fl = os.path.join(d, f)
1959 if (fl not in self.series and
1959 if (fl not in self.series and
1960 fl not in (self.statuspath, self.seriespath,
1960 fl not in (self.statuspath, self.seriespath,
1961 self.guardspath)
1961 self.guardspath)
1962 and not fl.startswith('.')):
1962 and not fl.startswith('.')):
1963 msng_list.append(fl)
1963 msng_list.append(fl)
1964 for x in sorted(msng_list):
1964 for x in sorted(msng_list):
1965 pfx = self.ui.verbose and ('D ') or ''
1965 pfx = self.ui.verbose and ('D ') or ''
1966 displayname(pfx, x, 'missing')
1966 displayname(pfx, x, 'missing')
1967
1967
1968 def issaveline(self, l):
1968 def issaveline(self, l):
1969 if l.name == '.hg.patches.save.line':
1969 if l.name == '.hg.patches.save.line':
1970 return True
1970 return True
1971
1971
1972 def qrepo(self, create=False):
1972 def qrepo(self, create=False):
1973 ui = self.baseui.copy()
1973 ui = self.baseui.copy()
1974 # copy back attributes set by ui.pager()
1974 # copy back attributes set by ui.pager()
1975 if self.ui.pageractive and not ui.pageractive:
1975 if self.ui.pageractive and not ui.pageractive:
1976 ui.pageractive = self.ui.pageractive
1976 ui.pageractive = self.ui.pageractive
1977 # internal config: ui.formatted
1977 # internal config: ui.formatted
1978 ui.setconfig('ui', 'formatted',
1978 ui.setconfig('ui', 'formatted',
1979 self.ui.config('ui', 'formatted'), 'mqpager')
1979 self.ui.config('ui', 'formatted'), 'mqpager')
1980 ui.setconfig('ui', 'interactive',
1980 ui.setconfig('ui', 'interactive',
1981 self.ui.config('ui', 'interactive'), 'mqpager')
1981 self.ui.config('ui', 'interactive'), 'mqpager')
1982 if create or os.path.isdir(self.join(".hg")):
1982 if create or os.path.isdir(self.join(".hg")):
1983 return hg.repository(ui, path=self.path, create=create)
1983 return hg.repository(ui, path=self.path, create=create)
1984
1984
1985 def restore(self, repo, rev, delete=None, qupdate=None):
1985 def restore(self, repo, rev, delete=None, qupdate=None):
1986 desc = repo[rev].description().strip()
1986 desc = repo[rev].description().strip()
1987 lines = desc.splitlines()
1987 lines = desc.splitlines()
1988 i = 0
1988 i = 0
1989 datastart = None
1989 datastart = None
1990 series = []
1990 series = []
1991 applied = []
1991 applied = []
1992 qpp = None
1992 qpp = None
1993 for i, line in enumerate(lines):
1993 for i, line in enumerate(lines):
1994 if line == 'Patch Data:':
1994 if line == 'Patch Data:':
1995 datastart = i + 1
1995 datastart = i + 1
1996 elif line.startswith('Dirstate:'):
1996 elif line.startswith('Dirstate:'):
1997 l = line.rstrip()
1997 l = line.rstrip()
1998 l = l[10:].split(' ')
1998 l = l[10:].split(' ')
1999 qpp = [bin(x) for x in l]
1999 qpp = [bin(x) for x in l]
2000 elif datastart is not None:
2000 elif datastart is not None:
2001 l = line.rstrip()
2001 l = line.rstrip()
2002 n, name = l.split(':', 1)
2002 n, name = l.split(':', 1)
2003 if n:
2003 if n:
2004 applied.append(statusentry(bin(n), name))
2004 applied.append(statusentry(bin(n), name))
2005 else:
2005 else:
2006 series.append(l)
2006 series.append(l)
2007 if datastart is None:
2007 if datastart is None:
2008 self.ui.warn(_("no saved patch data found\n"))
2008 self.ui.warn(_("no saved patch data found\n"))
2009 return 1
2009 return 1
2010 self.ui.warn(_("restoring status: %s\n") % lines[0])
2010 self.ui.warn(_("restoring status: %s\n") % lines[0])
2011 self.fullseries = series
2011 self.fullseries = series
2012 self.applied = applied
2012 self.applied = applied
2013 self.parseseries()
2013 self.parseseries()
2014 self.seriesdirty = True
2014 self.seriesdirty = True
2015 self.applieddirty = True
2015 self.applieddirty = True
2016 heads = repo.changelog.heads()
2016 heads = repo.changelog.heads()
2017 if delete:
2017 if delete:
2018 if rev not in heads:
2018 if rev not in heads:
2019 self.ui.warn(_("save entry has children, leaving it alone\n"))
2019 self.ui.warn(_("save entry has children, leaving it alone\n"))
2020 else:
2020 else:
2021 self.ui.warn(_("removing save entry %s\n") % short(rev))
2021 self.ui.warn(_("removing save entry %s\n") % short(rev))
2022 pp = repo.dirstate.parents()
2022 pp = repo.dirstate.parents()
2023 if rev in pp:
2023 if rev in pp:
2024 update = True
2024 update = True
2025 else:
2025 else:
2026 update = False
2026 update = False
2027 strip(self.ui, repo, [rev], update=update, backup=False)
2027 strip(self.ui, repo, [rev], update=update, backup=False)
2028 if qpp:
2028 if qpp:
2029 self.ui.warn(_("saved queue repository parents: %s %s\n") %
2029 self.ui.warn(_("saved queue repository parents: %s %s\n") %
2030 (short(qpp[0]), short(qpp[1])))
2030 (short(qpp[0]), short(qpp[1])))
2031 if qupdate:
2031 if qupdate:
2032 self.ui.status(_("updating queue directory\n"))
2032 self.ui.status(_("updating queue directory\n"))
2033 r = self.qrepo()
2033 r = self.qrepo()
2034 if not r:
2034 if not r:
2035 self.ui.warn(_("unable to load queue repository\n"))
2035 self.ui.warn(_("unable to load queue repository\n"))
2036 return 1
2036 return 1
2037 hg.clean(r, qpp[0])
2037 hg.clean(r, qpp[0])
2038
2038
2039 def save(self, repo, msg=None):
2039 def save(self, repo, msg=None):
2040 if not self.applied:
2040 if not self.applied:
2041 self.ui.warn(_("save: no patches applied, exiting\n"))
2041 self.ui.warn(_("save: no patches applied, exiting\n"))
2042 return 1
2042 return 1
2043 if self.issaveline(self.applied[-1]):
2043 if self.issaveline(self.applied[-1]):
2044 self.ui.warn(_("status is already saved\n"))
2044 self.ui.warn(_("status is already saved\n"))
2045 return 1
2045 return 1
2046
2046
2047 if not msg:
2047 if not msg:
2048 msg = _("hg patches saved state")
2048 msg = _("hg patches saved state")
2049 else:
2049 else:
2050 msg = "hg patches: " + msg.rstrip('\r\n')
2050 msg = "hg patches: " + msg.rstrip('\r\n')
2051 r = self.qrepo()
2051 r = self.qrepo()
2052 if r:
2052 if r:
2053 pp = r.dirstate.parents()
2053 pp = r.dirstate.parents()
2054 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
2054 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
2055 msg += "\n\nPatch Data:\n"
2055 msg += "\n\nPatch Data:\n"
2056 msg += ''.join('%s\n' % x for x in self.applied)
2056 msg += ''.join('%s\n' % x for x in self.applied)
2057 msg += ''.join(':%s\n' % x for x in self.fullseries)
2057 msg += ''.join(':%s\n' % x for x in self.fullseries)
2058 n = repo.commit(msg, force=True)
2058 n = repo.commit(msg, force=True)
2059 if not n:
2059 if not n:
2060 self.ui.warn(_("repo commit failed\n"))
2060 self.ui.warn(_("repo commit failed\n"))
2061 return 1
2061 return 1
2062 self.applied.append(statusentry(n, '.hg.patches.save.line'))
2062 self.applied.append(statusentry(n, '.hg.patches.save.line'))
2063 self.applieddirty = True
2063 self.applieddirty = True
2064 self.removeundo(repo)
2064 self.removeundo(repo)
2065
2065
2066 def fullseriesend(self):
2066 def fullseriesend(self):
2067 if self.applied:
2067 if self.applied:
2068 p = self.applied[-1].name
2068 p = self.applied[-1].name
2069 end = self.findseries(p)
2069 end = self.findseries(p)
2070 if end is None:
2070 if end is None:
2071 return len(self.fullseries)
2071 return len(self.fullseries)
2072 return end + 1
2072 return end + 1
2073 return 0
2073 return 0
2074
2074
2075 def seriesend(self, all_patches=False):
2075 def seriesend(self, all_patches=False):
2076 """If all_patches is False, return the index of the next pushable patch
2076 """If all_patches is False, return the index of the next pushable patch
2077 in the series, or the series length. If all_patches is True, return the
2077 in the series, or the series length. If all_patches is True, return the
2078 index of the first patch past the last applied one.
2078 index of the first patch past the last applied one.
2079 """
2079 """
2080 end = 0
2080 end = 0
2081 def nextpatch(start):
2081 def nextpatch(start):
2082 if all_patches or start >= len(self.series):
2082 if all_patches or start >= len(self.series):
2083 return start
2083 return start
2084 for i in xrange(start, len(self.series)):
2084 for i in xrange(start, len(self.series)):
2085 p, reason = self.pushable(i)
2085 p, reason = self.pushable(i)
2086 if p:
2086 if p:
2087 return i
2087 return i
2088 self.explainpushable(i)
2088 self.explainpushable(i)
2089 return len(self.series)
2089 return len(self.series)
2090 if self.applied:
2090 if self.applied:
2091 p = self.applied[-1].name
2091 p = self.applied[-1].name
2092 try:
2092 try:
2093 end = self.series.index(p)
2093 end = self.series.index(p)
2094 except ValueError:
2094 except ValueError:
2095 return 0
2095 return 0
2096 return nextpatch(end + 1)
2096 return nextpatch(end + 1)
2097 return nextpatch(end)
2097 return nextpatch(end)
2098
2098
2099 def appliedname(self, index):
2099 def appliedname(self, index):
2100 pname = self.applied[index].name
2100 pname = self.applied[index].name
2101 if not self.ui.verbose:
2101 if not self.ui.verbose:
2102 p = pname
2102 p = pname
2103 else:
2103 else:
2104 p = ("%d" % self.series.index(pname)) + " " + pname
2104 p = ("%d" % self.series.index(pname)) + " " + pname
2105 return p
2105 return p
2106
2106
2107 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
2107 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
2108 force=None, git=False):
2108 force=None, git=False):
2109 def checkseries(patchname):
2109 def checkseries(patchname):
2110 if patchname in self.series:
2110 if patchname in self.series:
2111 raise error.Abort(_('patch %s is already in the series file')
2111 raise error.Abort(_('patch %s is already in the series file')
2112 % patchname)
2112 % patchname)
2113
2113
2114 if rev:
2114 if rev:
2115 if files:
2115 if files:
2116 raise error.Abort(_('option "-r" not valid when importing '
2116 raise error.Abort(_('option "-r" not valid when importing '
2117 'files'))
2117 'files'))
2118 rev = scmutil.revrange(repo, rev)
2118 rev = scmutil.revrange(repo, rev)
2119 rev.sort(reverse=True)
2119 rev.sort(reverse=True)
2120 elif not files:
2120 elif not files:
2121 raise error.Abort(_('no files or revisions specified'))
2121 raise error.Abort(_('no files or revisions specified'))
2122 if (len(files) > 1 or len(rev) > 1) and patchname:
2122 if (len(files) > 1 or len(rev) > 1) and patchname:
2123 raise error.Abort(_('option "-n" not valid when importing multiple '
2123 raise error.Abort(_('option "-n" not valid when importing multiple '
2124 'patches'))
2124 'patches'))
2125 imported = []
2125 imported = []
2126 if rev:
2126 if rev:
2127 # If mq patches are applied, we can only import revisions
2127 # If mq patches are applied, we can only import revisions
2128 # that form a linear path to qbase.
2128 # that form a linear path to qbase.
2129 # Otherwise, they should form a linear path to a head.
2129 # Otherwise, they should form a linear path to a head.
2130 heads = repo.changelog.heads(repo.changelog.node(rev.first()))
2130 heads = repo.changelog.heads(repo.changelog.node(rev.first()))
2131 if len(heads) > 1:
2131 if len(heads) > 1:
2132 raise error.Abort(_('revision %d is the root of more than one '
2132 raise error.Abort(_('revision %d is the root of more than one '
2133 'branch') % rev.last())
2133 'branch') % rev.last())
2134 if self.applied:
2134 if self.applied:
2135 base = repo.changelog.node(rev.first())
2135 base = repo.changelog.node(rev.first())
2136 if base in [n.node for n in self.applied]:
2136 if base in [n.node for n in self.applied]:
2137 raise error.Abort(_('revision %d is already managed')
2137 raise error.Abort(_('revision %d is already managed')
2138 % rev.first())
2138 % rev.first())
2139 if heads != [self.applied[-1].node]:
2139 if heads != [self.applied[-1].node]:
2140 raise error.Abort(_('revision %d is not the parent of '
2140 raise error.Abort(_('revision %d is not the parent of '
2141 'the queue') % rev.first())
2141 'the queue') % rev.first())
2142 base = repo.changelog.rev(self.applied[0].node)
2142 base = repo.changelog.rev(self.applied[0].node)
2143 lastparent = repo.changelog.parentrevs(base)[0]
2143 lastparent = repo.changelog.parentrevs(base)[0]
2144 else:
2144 else:
2145 if heads != [repo.changelog.node(rev.first())]:
2145 if heads != [repo.changelog.node(rev.first())]:
2146 raise error.Abort(_('revision %d has unmanaged children')
2146 raise error.Abort(_('revision %d has unmanaged children')
2147 % rev.first())
2147 % rev.first())
2148 lastparent = None
2148 lastparent = None
2149
2149
2150 diffopts = self.diffopts({'git': git})
2150 diffopts = self.diffopts({'git': git})
2151 with repo.transaction('qimport') as tr:
2151 with repo.transaction('qimport') as tr:
2152 for r in rev:
2152 for r in rev:
2153 if not repo[r].mutable():
2153 if not repo[r].mutable():
2154 raise error.Abort(_('revision %d is not mutable') % r,
2154 raise error.Abort(_('revision %d is not mutable') % r,
2155 hint=_("see 'hg help phases' "
2155 hint=_("see 'hg help phases' "
2156 'for details'))
2156 'for details'))
2157 p1, p2 = repo.changelog.parentrevs(r)
2157 p1, p2 = repo.changelog.parentrevs(r)
2158 n = repo.changelog.node(r)
2158 n = repo.changelog.node(r)
2159 if p2 != nullrev:
2159 if p2 != nullrev:
2160 raise error.Abort(_('cannot import merge revision %d')
2160 raise error.Abort(_('cannot import merge revision %d')
2161 % r)
2161 % r)
2162 if lastparent and lastparent != r:
2162 if lastparent and lastparent != r:
2163 raise error.Abort(_('revision %d is not the parent of '
2163 raise error.Abort(_('revision %d is not the parent of '
2164 '%d')
2164 '%d')
2165 % (r, lastparent))
2165 % (r, lastparent))
2166 lastparent = p1
2166 lastparent = p1
2167
2167
2168 if not patchname:
2168 if not patchname:
2169 patchname = self.makepatchname(
2169 patchname = self.makepatchname(
2170 repo[r].description().split('\n', 1)[0],
2170 repo[r].description().split('\n', 1)[0],
2171 '%d.diff' % r)
2171 '%d.diff' % r)
2172 checkseries(patchname)
2172 checkseries(patchname)
2173 self.checkpatchname(patchname, force)
2173 self.checkpatchname(patchname, force)
2174 self.fullseries.insert(0, patchname)
2174 self.fullseries.insert(0, patchname)
2175
2175
2176 patchf = self.opener(patchname, "w")
2176 patchf = self.opener(patchname, "w")
2177 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
2177 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
2178 patchf.close()
2178 patchf.close()
2179
2179
2180 se = statusentry(n, patchname)
2180 se = statusentry(n, patchname)
2181 self.applied.insert(0, se)
2181 self.applied.insert(0, se)
2182
2182
2183 self.added.append(patchname)
2183 self.added.append(patchname)
2184 imported.append(patchname)
2184 imported.append(patchname)
2185 patchname = None
2185 patchname = None
2186 if rev and repo.ui.configbool('mq', 'secret'):
2186 if rev and repo.ui.configbool('mq', 'secret'):
2187 # if we added anything with --rev, move the secret root
2187 # if we added anything with --rev, move the secret root
2188 phases.retractboundary(repo, tr, phases.secret, [n])
2188 phases.retractboundary(repo, tr, phases.secret, [n])
2189 self.parseseries()
2189 self.parseseries()
2190 self.applieddirty = True
2190 self.applieddirty = True
2191 self.seriesdirty = True
2191 self.seriesdirty = True
2192
2192
2193 for i, filename in enumerate(files):
2193 for i, filename in enumerate(files):
2194 if existing:
2194 if existing:
2195 if filename == '-':
2195 if filename == '-':
2196 raise error.Abort(_('-e is incompatible with import from -')
2196 raise error.Abort(_('-e is incompatible with import from -')
2197 )
2197 )
2198 filename = normname(filename)
2198 filename = normname(filename)
2199 self.checkreservedname(filename)
2199 self.checkreservedname(filename)
2200 if util.url(filename).islocal():
2200 if util.url(filename).islocal():
2201 originpath = self.join(filename)
2201 originpath = self.join(filename)
2202 if not os.path.isfile(originpath):
2202 if not os.path.isfile(originpath):
2203 raise error.Abort(
2203 raise error.Abort(
2204 _("patch %s does not exist") % filename)
2204 _("patch %s does not exist") % filename)
2205
2205
2206 if patchname:
2206 if patchname:
2207 self.checkpatchname(patchname, force)
2207 self.checkpatchname(patchname, force)
2208
2208
2209 self.ui.write(_('renaming %s to %s\n')
2209 self.ui.write(_('renaming %s to %s\n')
2210 % (filename, patchname))
2210 % (filename, patchname))
2211 util.rename(originpath, self.join(patchname))
2211 util.rename(originpath, self.join(patchname))
2212 else:
2212 else:
2213 patchname = filename
2213 patchname = filename
2214
2214
2215 else:
2215 else:
2216 if filename == '-' and not patchname:
2216 if filename == '-' and not patchname:
2217 raise error.Abort(_('need --name to import a patch from -'))
2217 raise error.Abort(_('need --name to import a patch from -'))
2218 elif not patchname:
2218 elif not patchname:
2219 patchname = normname(os.path.basename(filename.rstrip('/')))
2219 patchname = normname(os.path.basename(filename.rstrip('/')))
2220 self.checkpatchname(patchname, force)
2220 self.checkpatchname(patchname, force)
2221 try:
2221 try:
2222 if filename == '-':
2222 if filename == '-':
2223 text = self.ui.fin.read()
2223 text = self.ui.fin.read()
2224 else:
2224 else:
2225 fp = hg.openpath(self.ui, filename)
2225 fp = hg.openpath(self.ui, filename)
2226 text = fp.read()
2226 text = fp.read()
2227 fp.close()
2227 fp.close()
2228 except (OSError, IOError):
2228 except (OSError, IOError):
2229 raise error.Abort(_("unable to read file %s") % filename)
2229 raise error.Abort(_("unable to read file %s") % filename)
2230 patchf = self.opener(patchname, "w")
2230 patchf = self.opener(patchname, "w")
2231 patchf.write(text)
2231 patchf.write(text)
2232 patchf.close()
2232 patchf.close()
2233 if not force:
2233 if not force:
2234 checkseries(patchname)
2234 checkseries(patchname)
2235 if patchname not in self.series:
2235 if patchname not in self.series:
2236 index = self.fullseriesend() + i
2236 index = self.fullseriesend() + i
2237 self.fullseries[index:index] = [patchname]
2237 self.fullseries[index:index] = [patchname]
2238 self.parseseries()
2238 self.parseseries()
2239 self.seriesdirty = True
2239 self.seriesdirty = True
2240 self.ui.warn(_("adding %s to series file\n") % patchname)
2240 self.ui.warn(_("adding %s to series file\n") % patchname)
2241 self.added.append(patchname)
2241 self.added.append(patchname)
2242 imported.append(patchname)
2242 imported.append(patchname)
2243 patchname = None
2243 patchname = None
2244
2244
2245 self.removeundo(repo)
2245 self.removeundo(repo)
2246 return imported
2246 return imported
2247
2247
2248 def fixkeepchangesopts(ui, opts):
2248 def fixkeepchangesopts(ui, opts):
2249 if (not ui.configbool('mq', 'keepchanges') or opts.get('force')
2249 if (not ui.configbool('mq', 'keepchanges') or opts.get('force')
2250 or opts.get('exact')):
2250 or opts.get('exact')):
2251 return opts
2251 return opts
2252 opts = dict(opts)
2252 opts = dict(opts)
2253 opts['keep_changes'] = True
2253 opts['keep_changes'] = True
2254 return opts
2254 return opts
2255
2255
2256 @command("qdelete|qremove|qrm",
2256 @command("qdelete|qremove|qrm",
2257 [('k', 'keep', None, _('keep patch file')),
2257 [('k', 'keep', None, _('keep patch file')),
2258 ('r', 'rev', [],
2258 ('r', 'rev', [],
2259 _('stop managing a revision (DEPRECATED)'), _('REV'))],
2259 _('stop managing a revision (DEPRECATED)'), _('REV'))],
2260 _('hg qdelete [-k] [PATCH]...'))
2260 _('hg qdelete [-k] [PATCH]...'))
2261 def delete(ui, repo, *patches, **opts):
2261 def delete(ui, repo, *patches, **opts):
2262 """remove patches from queue
2262 """remove patches from queue
2263
2263
2264 The patches must not be applied, and at least one patch is required. Exact
2264 The patches must not be applied, and at least one patch is required. Exact
2265 patch identifiers must be given. With -k/--keep, the patch files are
2265 patch identifiers must be given. With -k/--keep, the patch files are
2266 preserved in the patch directory.
2266 preserved in the patch directory.
2267
2267
2268 To stop managing a patch and move it into permanent history,
2268 To stop managing a patch and move it into permanent history,
2269 use the :hg:`qfinish` command."""
2269 use the :hg:`qfinish` command."""
2270 q = repo.mq
2270 q = repo.mq
2271 q.delete(repo, patches, pycompat.byteskwargs(opts))
2271 q.delete(repo, patches, pycompat.byteskwargs(opts))
2272 q.savedirty()
2272 q.savedirty()
2273 return 0
2273 return 0
2274
2274
2275 @command("qapplied",
2275 @command("qapplied",
2276 [('1', 'last', None, _('show only the preceding applied patch'))
2276 [('1', 'last', None, _('show only the preceding applied patch'))
2277 ] + seriesopts,
2277 ] + seriesopts,
2278 _('hg qapplied [-1] [-s] [PATCH]'))
2278 _('hg qapplied [-1] [-s] [PATCH]'))
2279 def applied(ui, repo, patch=None, **opts):
2279 def applied(ui, repo, patch=None, **opts):
2280 """print the patches already applied
2280 """print the patches already applied
2281
2281
2282 Returns 0 on success."""
2282 Returns 0 on success."""
2283
2283
2284 q = repo.mq
2284 q = repo.mq
2285 opts = pycompat.byteskwargs(opts)
2285 opts = pycompat.byteskwargs(opts)
2286
2286
2287 if patch:
2287 if patch:
2288 if patch not in q.series:
2288 if patch not in q.series:
2289 raise error.Abort(_("patch %s is not in series file") % patch)
2289 raise error.Abort(_("patch %s is not in series file") % patch)
2290 end = q.series.index(patch) + 1
2290 end = q.series.index(patch) + 1
2291 else:
2291 else:
2292 end = q.seriesend(True)
2292 end = q.seriesend(True)
2293
2293
2294 if opts.get('last') and not end:
2294 if opts.get('last') and not end:
2295 ui.write(_("no patches applied\n"))
2295 ui.write(_("no patches applied\n"))
2296 return 1
2296 return 1
2297 elif opts.get('last') and end == 1:
2297 elif opts.get('last') and end == 1:
2298 ui.write(_("only one patch applied\n"))
2298 ui.write(_("only one patch applied\n"))
2299 return 1
2299 return 1
2300 elif opts.get('last'):
2300 elif opts.get('last'):
2301 start = end - 2
2301 start = end - 2
2302 end = 1
2302 end = 1
2303 else:
2303 else:
2304 start = 0
2304 start = 0
2305
2305
2306 q.qseries(repo, length=end, start=start, status='A',
2306 q.qseries(repo, length=end, start=start, status='A',
2307 summary=opts.get('summary'))
2307 summary=opts.get('summary'))
2308
2308
2309
2309
2310 @command("qunapplied",
2310 @command("qunapplied",
2311 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
2311 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
2312 _('hg qunapplied [-1] [-s] [PATCH]'))
2312 _('hg qunapplied [-1] [-s] [PATCH]'))
2313 def unapplied(ui, repo, patch=None, **opts):
2313 def unapplied(ui, repo, patch=None, **opts):
2314 """print the patches not yet applied
2314 """print the patches not yet applied
2315
2315
2316 Returns 0 on success."""
2316 Returns 0 on success."""
2317
2317
2318 q = repo.mq
2318 q = repo.mq
2319 opts = pycompat.byteskwargs(opts)
2319 opts = pycompat.byteskwargs(opts)
2320 if patch:
2320 if patch:
2321 if patch not in q.series:
2321 if patch not in q.series:
2322 raise error.Abort(_("patch %s is not in series file") % patch)
2322 raise error.Abort(_("patch %s is not in series file") % patch)
2323 start = q.series.index(patch) + 1
2323 start = q.series.index(patch) + 1
2324 else:
2324 else:
2325 start = q.seriesend(True)
2325 start = q.seriesend(True)
2326
2326
2327 if start == len(q.series) and opts.get('first'):
2327 if start == len(q.series) and opts.get('first'):
2328 ui.write(_("all patches applied\n"))
2328 ui.write(_("all patches applied\n"))
2329 return 1
2329 return 1
2330
2330
2331 if opts.get('first'):
2331 if opts.get('first'):
2332 length = 1
2332 length = 1
2333 else:
2333 else:
2334 length = None
2334 length = None
2335 q.qseries(repo, start=start, length=length, status='U',
2335 q.qseries(repo, start=start, length=length, status='U',
2336 summary=opts.get('summary'))
2336 summary=opts.get('summary'))
2337
2337
2338 @command("qimport",
2338 @command("qimport",
2339 [('e', 'existing', None, _('import file in patch directory')),
2339 [('e', 'existing', None, _('import file in patch directory')),
2340 ('n', 'name', '',
2340 ('n', 'name', '',
2341 _('name of patch file'), _('NAME')),
2341 _('name of patch file'), _('NAME')),
2342 ('f', 'force', None, _('overwrite existing files')),
2342 ('f', 'force', None, _('overwrite existing files')),
2343 ('r', 'rev', [],
2343 ('r', 'rev', [],
2344 _('place existing revisions under mq control'), _('REV')),
2344 _('place existing revisions under mq control'), _('REV')),
2345 ('g', 'git', None, _('use git extended diff format')),
2345 ('g', 'git', None, _('use git extended diff format')),
2346 ('P', 'push', None, _('qpush after importing'))],
2346 ('P', 'push', None, _('qpush after importing'))],
2347 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... [FILE]...'))
2347 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... [FILE]...'))
2348 def qimport(ui, repo, *filename, **opts):
2348 def qimport(ui, repo, *filename, **opts):
2349 """import a patch or existing changeset
2349 """import a patch or existing changeset
2350
2350
2351 The patch is inserted into the series after the last applied
2351 The patch is inserted into the series after the last applied
2352 patch. If no patches have been applied, qimport prepends the patch
2352 patch. If no patches have been applied, qimport prepends the patch
2353 to the series.
2353 to the series.
2354
2354
2355 The patch will have the same name as its source file unless you
2355 The patch will have the same name as its source file unless you
2356 give it a new one with -n/--name.
2356 give it a new one with -n/--name.
2357
2357
2358 You can register an existing patch inside the patch directory with
2358 You can register an existing patch inside the patch directory with
2359 the -e/--existing flag.
2359 the -e/--existing flag.
2360
2360
2361 With -f/--force, an existing patch of the same name will be
2361 With -f/--force, an existing patch of the same name will be
2362 overwritten.
2362 overwritten.
2363
2363
2364 An existing changeset may be placed under mq control with -r/--rev
2364 An existing changeset may be placed under mq control with -r/--rev
2365 (e.g. qimport --rev . -n patch will place the current revision
2365 (e.g. qimport --rev . -n patch will place the current revision
2366 under mq control). With -g/--git, patches imported with --rev will
2366 under mq control). With -g/--git, patches imported with --rev will
2367 use the git diff format. See the diffs help topic for information
2367 use the git diff format. See the diffs help topic for information
2368 on why this is important for preserving rename/copy information
2368 on why this is important for preserving rename/copy information
2369 and permission changes. Use :hg:`qfinish` to remove changesets
2369 and permission changes. Use :hg:`qfinish` to remove changesets
2370 from mq control.
2370 from mq control.
2371
2371
2372 To import a patch from standard input, pass - as the patch file.
2372 To import a patch from standard input, pass - as the patch file.
2373 When importing from standard input, a patch name must be specified
2373 When importing from standard input, a patch name must be specified
2374 using the --name flag.
2374 using the --name flag.
2375
2375
2376 To import an existing patch while renaming it::
2376 To import an existing patch while renaming it::
2377
2377
2378 hg qimport -e existing-patch -n new-name
2378 hg qimport -e existing-patch -n new-name
2379
2379
2380 Returns 0 if import succeeded.
2380 Returns 0 if import succeeded.
2381 """
2381 """
2382 opts = pycompat.byteskwargs(opts)
2382 opts = pycompat.byteskwargs(opts)
2383 with repo.lock(): # cause this may move phase
2383 with repo.lock(): # cause this may move phase
2384 q = repo.mq
2384 q = repo.mq
2385 try:
2385 try:
2386 imported = q.qimport(
2386 imported = q.qimport(
2387 repo, filename, patchname=opts.get('name'),
2387 repo, filename, patchname=opts.get('name'),
2388 existing=opts.get('existing'), force=opts.get('force'),
2388 existing=opts.get('existing'), force=opts.get('force'),
2389 rev=opts.get('rev'), git=opts.get('git'))
2389 rev=opts.get('rev'), git=opts.get('git'))
2390 finally:
2390 finally:
2391 q.savedirty()
2391 q.savedirty()
2392
2392
2393 if imported and opts.get('push') and not opts.get('rev'):
2393 if imported and opts.get('push') and not opts.get('rev'):
2394 return q.push(repo, imported[-1])
2394 return q.push(repo, imported[-1])
2395 return 0
2395 return 0
2396
2396
2397 def qinit(ui, repo, create):
2397 def qinit(ui, repo, create):
2398 """initialize a new queue repository
2398 """initialize a new queue repository
2399
2399
2400 This command also creates a series file for ordering patches, and
2400 This command also creates a series file for ordering patches, and
2401 an mq-specific .hgignore file in the queue repository, to exclude
2401 an mq-specific .hgignore file in the queue repository, to exclude
2402 the status and guards files (these contain mostly transient state).
2402 the status and guards files (these contain mostly transient state).
2403
2403
2404 Returns 0 if initialization succeeded."""
2404 Returns 0 if initialization succeeded."""
2405 q = repo.mq
2405 q = repo.mq
2406 r = q.init(repo, create)
2406 r = q.init(repo, create)
2407 q.savedirty()
2407 q.savedirty()
2408 if r:
2408 if r:
2409 if not os.path.exists(r.wjoin('.hgignore')):
2409 if not os.path.exists(r.wjoin('.hgignore')):
2410 fp = r.wvfs('.hgignore', 'w')
2410 fp = r.wvfs('.hgignore', 'w')
2411 fp.write('^\\.hg\n')
2411 fp.write('^\\.hg\n')
2412 fp.write('^\\.mq\n')
2412 fp.write('^\\.mq\n')
2413 fp.write('syntax: glob\n')
2413 fp.write('syntax: glob\n')
2414 fp.write('status\n')
2414 fp.write('status\n')
2415 fp.write('guards\n')
2415 fp.write('guards\n')
2416 fp.close()
2416 fp.close()
2417 if not os.path.exists(r.wjoin('series')):
2417 if not os.path.exists(r.wjoin('series')):
2418 r.wvfs('series', 'w').close()
2418 r.wvfs('series', 'w').close()
2419 r[None].add(['.hgignore', 'series'])
2419 r[None].add(['.hgignore', 'series'])
2420 commands.add(ui, r)
2420 commands.add(ui, r)
2421 return 0
2421 return 0
2422
2422
2423 @command("^qinit",
2423 @command("^qinit",
2424 [('c', 'create-repo', None, _('create queue repository'))],
2424 [('c', 'create-repo', None, _('create queue repository'))],
2425 _('hg qinit [-c]'))
2425 _('hg qinit [-c]'))
2426 def init(ui, repo, **opts):
2426 def init(ui, repo, **opts):
2427 """init a new queue repository (DEPRECATED)
2427 """init a new queue repository (DEPRECATED)
2428
2428
2429 The queue repository is unversioned by default. If
2429 The queue repository is unversioned by default. If
2430 -c/--create-repo is specified, qinit will create a separate nested
2430 -c/--create-repo is specified, qinit will create a separate nested
2431 repository for patches (qinit -c may also be run later to convert
2431 repository for patches (qinit -c may also be run later to convert
2432 an unversioned patch repository into a versioned one). You can use
2432 an unversioned patch repository into a versioned one). You can use
2433 qcommit to commit changes to this queue repository.
2433 qcommit to commit changes to this queue repository.
2434
2434
2435 This command is deprecated. Without -c, it's implied by other relevant
2435 This command is deprecated. Without -c, it's implied by other relevant
2436 commands. With -c, use :hg:`init --mq` instead."""
2436 commands. With -c, use :hg:`init --mq` instead."""
2437 return qinit(ui, repo, create=opts.get(r'create_repo'))
2437 return qinit(ui, repo, create=opts.get(r'create_repo'))
2438
2438
2439 @command("qclone",
2439 @command("qclone",
2440 [('', 'pull', None, _('use pull protocol to copy metadata')),
2440 [('', 'pull', None, _('use pull protocol to copy metadata')),
2441 ('U', 'noupdate', None,
2441 ('U', 'noupdate', None,
2442 _('do not update the new working directories')),
2442 _('do not update the new working directories')),
2443 ('', 'uncompressed', None,
2443 ('', 'uncompressed', None,
2444 _('use uncompressed transfer (fast over LAN)')),
2444 _('use uncompressed transfer (fast over LAN)')),
2445 ('p', 'patches', '',
2445 ('p', 'patches', '',
2446 _('location of source patch repository'), _('REPO')),
2446 _('location of source patch repository'), _('REPO')),
2447 ] + cmdutil.remoteopts,
2447 ] + cmdutil.remoteopts,
2448 _('hg qclone [OPTION]... SOURCE [DEST]'),
2448 _('hg qclone [OPTION]... SOURCE [DEST]'),
2449 norepo=True)
2449 norepo=True)
2450 def clone(ui, source, dest=None, **opts):
2450 def clone(ui, source, dest=None, **opts):
2451 '''clone main and patch repository at same time
2451 '''clone main and patch repository at same time
2452
2452
2453 If source is local, destination will have no patches applied. If
2453 If source is local, destination will have no patches applied. If
2454 source is remote, this command can not check if patches are
2454 source is remote, this command can not check if patches are
2455 applied in source, so cannot guarantee that patches are not
2455 applied in source, so cannot guarantee that patches are not
2456 applied in destination. If you clone remote repository, be sure
2456 applied in destination. If you clone remote repository, be sure
2457 before that it has no patches applied.
2457 before that it has no patches applied.
2458
2458
2459 Source patch repository is looked for in <src>/.hg/patches by
2459 Source patch repository is looked for in <src>/.hg/patches by
2460 default. Use -p <url> to change.
2460 default. Use -p <url> to change.
2461
2461
2462 The patch directory must be a nested Mercurial repository, as
2462 The patch directory must be a nested Mercurial repository, as
2463 would be created by :hg:`init --mq`.
2463 would be created by :hg:`init --mq`.
2464
2464
2465 Return 0 on success.
2465 Return 0 on success.
2466 '''
2466 '''
2467 opts = pycompat.byteskwargs(opts)
2467 opts = pycompat.byteskwargs(opts)
2468 def patchdir(repo):
2468 def patchdir(repo):
2469 """compute a patch repo url from a repo object"""
2469 """compute a patch repo url from a repo object"""
2470 url = repo.url()
2470 url = repo.url()
2471 if url.endswith('/'):
2471 if url.endswith('/'):
2472 url = url[:-1]
2472 url = url[:-1]
2473 return url + '/.hg/patches'
2473 return url + '/.hg/patches'
2474
2474
2475 # main repo (destination and sources)
2475 # main repo (destination and sources)
2476 if dest is None:
2476 if dest is None:
2477 dest = hg.defaultdest(source)
2477 dest = hg.defaultdest(source)
2478 sr = hg.peer(ui, opts, ui.expandpath(source))
2478 sr = hg.peer(ui, opts, ui.expandpath(source))
2479
2479
2480 # patches repo (source only)
2480 # patches repo (source only)
2481 if opts.get('patches'):
2481 if opts.get('patches'):
2482 patchespath = ui.expandpath(opts.get('patches'))
2482 patchespath = ui.expandpath(opts.get('patches'))
2483 else:
2483 else:
2484 patchespath = patchdir(sr)
2484 patchespath = patchdir(sr)
2485 try:
2485 try:
2486 hg.peer(ui, opts, patchespath)
2486 hg.peer(ui, opts, patchespath)
2487 except error.RepoError:
2487 except error.RepoError:
2488 raise error.Abort(_('versioned patch repository not found'
2488 raise error.Abort(_('versioned patch repository not found'
2489 ' (see init --mq)'))
2489 ' (see init --mq)'))
2490 qbase, destrev = None, None
2490 qbase, destrev = None, None
2491 if sr.local():
2491 if sr.local():
2492 repo = sr.local()
2492 repo = sr.local()
2493 if repo.mq.applied and repo[qbase].phase() != phases.secret:
2493 if repo.mq.applied and repo[qbase].phase() != phases.secret:
2494 qbase = repo.mq.applied[0].node
2494 qbase = repo.mq.applied[0].node
2495 if not hg.islocal(dest):
2495 if not hg.islocal(dest):
2496 heads = set(repo.heads())
2496 heads = set(repo.heads())
2497 destrev = list(heads.difference(repo.heads(qbase)))
2497 destrev = list(heads.difference(repo.heads(qbase)))
2498 destrev.append(repo.changelog.parents(qbase)[0])
2498 destrev.append(repo.changelog.parents(qbase)[0])
2499 elif sr.capable('lookup'):
2499 elif sr.capable('lookup'):
2500 try:
2500 try:
2501 qbase = sr.lookup('qbase')
2501 qbase = sr.lookup('qbase')
2502 except error.RepoError:
2502 except error.RepoError:
2503 pass
2503 pass
2504
2504
2505 ui.note(_('cloning main repository\n'))
2505 ui.note(_('cloning main repository\n'))
2506 sr, dr = hg.clone(ui, opts, sr.url(), dest,
2506 sr, dr = hg.clone(ui, opts, sr.url(), dest,
2507 pull=opts.get('pull'),
2507 pull=opts.get('pull'),
2508 rev=destrev,
2508 revs=destrev,
2509 update=False,
2509 update=False,
2510 stream=opts.get('uncompressed'))
2510 stream=opts.get('uncompressed'))
2511
2511
2512 ui.note(_('cloning patch repository\n'))
2512 ui.note(_('cloning patch repository\n'))
2513 hg.clone(ui, opts, opts.get('patches') or patchdir(sr), patchdir(dr),
2513 hg.clone(ui, opts, opts.get('patches') or patchdir(sr), patchdir(dr),
2514 pull=opts.get('pull'), update=not opts.get('noupdate'),
2514 pull=opts.get('pull'), update=not opts.get('noupdate'),
2515 stream=opts.get('uncompressed'))
2515 stream=opts.get('uncompressed'))
2516
2516
2517 if dr.local():
2517 if dr.local():
2518 repo = dr.local()
2518 repo = dr.local()
2519 if qbase:
2519 if qbase:
2520 ui.note(_('stripping applied patches from destination '
2520 ui.note(_('stripping applied patches from destination '
2521 'repository\n'))
2521 'repository\n'))
2522 strip(ui, repo, [qbase], update=False, backup=None)
2522 strip(ui, repo, [qbase], update=False, backup=None)
2523 if not opts.get('noupdate'):
2523 if not opts.get('noupdate'):
2524 ui.note(_('updating destination repository\n'))
2524 ui.note(_('updating destination repository\n'))
2525 hg.update(repo, repo.changelog.tip())
2525 hg.update(repo, repo.changelog.tip())
2526
2526
2527 @command("qcommit|qci",
2527 @command("qcommit|qci",
2528 commands.table["^commit|ci"][1],
2528 commands.table["^commit|ci"][1],
2529 _('hg qcommit [OPTION]... [FILE]...'),
2529 _('hg qcommit [OPTION]... [FILE]...'),
2530 inferrepo=True)
2530 inferrepo=True)
2531 def commit(ui, repo, *pats, **opts):
2531 def commit(ui, repo, *pats, **opts):
2532 """commit changes in the queue repository (DEPRECATED)
2532 """commit changes in the queue repository (DEPRECATED)
2533
2533
2534 This command is deprecated; use :hg:`commit --mq` instead."""
2534 This command is deprecated; use :hg:`commit --mq` instead."""
2535 q = repo.mq
2535 q = repo.mq
2536 r = q.qrepo()
2536 r = q.qrepo()
2537 if not r:
2537 if not r:
2538 raise error.Abort('no queue repository')
2538 raise error.Abort('no queue repository')
2539 commands.commit(r.ui, r, *pats, **opts)
2539 commands.commit(r.ui, r, *pats, **opts)
2540
2540
2541 @command("qseries",
2541 @command("qseries",
2542 [('m', 'missing', None, _('print patches not in series')),
2542 [('m', 'missing', None, _('print patches not in series')),
2543 ] + seriesopts,
2543 ] + seriesopts,
2544 _('hg qseries [-ms]'))
2544 _('hg qseries [-ms]'))
2545 def series(ui, repo, **opts):
2545 def series(ui, repo, **opts):
2546 """print the entire series file
2546 """print the entire series file
2547
2547
2548 Returns 0 on success."""
2548 Returns 0 on success."""
2549 repo.mq.qseries(repo, missing=opts.get(r'missing'),
2549 repo.mq.qseries(repo, missing=opts.get(r'missing'),
2550 summary=opts.get(r'summary'))
2550 summary=opts.get(r'summary'))
2551 return 0
2551 return 0
2552
2552
2553 @command("qtop", seriesopts, _('hg qtop [-s]'))
2553 @command("qtop", seriesopts, _('hg qtop [-s]'))
2554 def top(ui, repo, **opts):
2554 def top(ui, repo, **opts):
2555 """print the name of the current patch
2555 """print the name of the current patch
2556
2556
2557 Returns 0 on success."""
2557 Returns 0 on success."""
2558 q = repo.mq
2558 q = repo.mq
2559 if q.applied:
2559 if q.applied:
2560 t = q.seriesend(True)
2560 t = q.seriesend(True)
2561 else:
2561 else:
2562 t = 0
2562 t = 0
2563
2563
2564 if t:
2564 if t:
2565 q.qseries(repo, start=t - 1, length=1, status='A',
2565 q.qseries(repo, start=t - 1, length=1, status='A',
2566 summary=opts.get(r'summary'))
2566 summary=opts.get(r'summary'))
2567 else:
2567 else:
2568 ui.write(_("no patches applied\n"))
2568 ui.write(_("no patches applied\n"))
2569 return 1
2569 return 1
2570
2570
2571 @command("qnext", seriesopts, _('hg qnext [-s]'))
2571 @command("qnext", seriesopts, _('hg qnext [-s]'))
2572 def next(ui, repo, **opts):
2572 def next(ui, repo, **opts):
2573 """print the name of the next pushable patch
2573 """print the name of the next pushable patch
2574
2574
2575 Returns 0 on success."""
2575 Returns 0 on success."""
2576 q = repo.mq
2576 q = repo.mq
2577 end = q.seriesend()
2577 end = q.seriesend()
2578 if end == len(q.series):
2578 if end == len(q.series):
2579 ui.write(_("all patches applied\n"))
2579 ui.write(_("all patches applied\n"))
2580 return 1
2580 return 1
2581 q.qseries(repo, start=end, length=1, summary=opts.get(r'summary'))
2581 q.qseries(repo, start=end, length=1, summary=opts.get(r'summary'))
2582
2582
2583 @command("qprev", seriesopts, _('hg qprev [-s]'))
2583 @command("qprev", seriesopts, _('hg qprev [-s]'))
2584 def prev(ui, repo, **opts):
2584 def prev(ui, repo, **opts):
2585 """print the name of the preceding applied patch
2585 """print the name of the preceding applied patch
2586
2586
2587 Returns 0 on success."""
2587 Returns 0 on success."""
2588 q = repo.mq
2588 q = repo.mq
2589 l = len(q.applied)
2589 l = len(q.applied)
2590 if l == 1:
2590 if l == 1:
2591 ui.write(_("only one patch applied\n"))
2591 ui.write(_("only one patch applied\n"))
2592 return 1
2592 return 1
2593 if not l:
2593 if not l:
2594 ui.write(_("no patches applied\n"))
2594 ui.write(_("no patches applied\n"))
2595 return 1
2595 return 1
2596 idx = q.series.index(q.applied[-2].name)
2596 idx = q.series.index(q.applied[-2].name)
2597 q.qseries(repo, start=idx, length=1, status='A',
2597 q.qseries(repo, start=idx, length=1, status='A',
2598 summary=opts.get(r'summary'))
2598 summary=opts.get(r'summary'))
2599
2599
2600 def setupheaderopts(ui, opts):
2600 def setupheaderopts(ui, opts):
2601 if not opts.get('user') and opts.get('currentuser'):
2601 if not opts.get('user') and opts.get('currentuser'):
2602 opts['user'] = ui.username()
2602 opts['user'] = ui.username()
2603 if not opts.get('date') and opts.get('currentdate'):
2603 if not opts.get('date') and opts.get('currentdate'):
2604 opts['date'] = "%d %d" % dateutil.makedate()
2604 opts['date'] = "%d %d" % dateutil.makedate()
2605
2605
2606 @command("^qnew",
2606 @command("^qnew",
2607 [('e', 'edit', None, _('invoke editor on commit messages')),
2607 [('e', 'edit', None, _('invoke editor on commit messages')),
2608 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2608 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2609 ('g', 'git', None, _('use git extended diff format')),
2609 ('g', 'git', None, _('use git extended diff format')),
2610 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2610 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2611 ('u', 'user', '',
2611 ('u', 'user', '',
2612 _('add "From: <USER>" to patch'), _('USER')),
2612 _('add "From: <USER>" to patch'), _('USER')),
2613 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2613 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2614 ('d', 'date', '',
2614 ('d', 'date', '',
2615 _('add "Date: <DATE>" to patch'), _('DATE'))
2615 _('add "Date: <DATE>" to patch'), _('DATE'))
2616 ] + cmdutil.walkopts + cmdutil.commitopts,
2616 ] + cmdutil.walkopts + cmdutil.commitopts,
2617 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'),
2617 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'),
2618 inferrepo=True)
2618 inferrepo=True)
2619 def new(ui, repo, patch, *args, **opts):
2619 def new(ui, repo, patch, *args, **opts):
2620 """create a new patch
2620 """create a new patch
2621
2621
2622 qnew creates a new patch on top of the currently-applied patch (if
2622 qnew creates a new patch on top of the currently-applied patch (if
2623 any). The patch will be initialized with any outstanding changes
2623 any). The patch will be initialized with any outstanding changes
2624 in the working directory. You may also use -I/--include,
2624 in the working directory. You may also use -I/--include,
2625 -X/--exclude, and/or a list of files after the patch name to add
2625 -X/--exclude, and/or a list of files after the patch name to add
2626 only changes to matching files to the new patch, leaving the rest
2626 only changes to matching files to the new patch, leaving the rest
2627 as uncommitted modifications.
2627 as uncommitted modifications.
2628
2628
2629 -u/--user and -d/--date can be used to set the (given) user and
2629 -u/--user and -d/--date can be used to set the (given) user and
2630 date, respectively. -U/--currentuser and -D/--currentdate set user
2630 date, respectively. -U/--currentuser and -D/--currentdate set user
2631 to current user and date to current date.
2631 to current user and date to current date.
2632
2632
2633 -e/--edit, -m/--message or -l/--logfile set the patch header as
2633 -e/--edit, -m/--message or -l/--logfile set the patch header as
2634 well as the commit message. If none is specified, the header is
2634 well as the commit message. If none is specified, the header is
2635 empty and the commit message is '[mq]: PATCH'.
2635 empty and the commit message is '[mq]: PATCH'.
2636
2636
2637 Use the -g/--git option to keep the patch in the git extended diff
2637 Use the -g/--git option to keep the patch in the git extended diff
2638 format. Read the diffs help topic for more information on why this
2638 format. Read the diffs help topic for more information on why this
2639 is important for preserving permission changes and copy/rename
2639 is important for preserving permission changes and copy/rename
2640 information.
2640 information.
2641
2641
2642 Returns 0 on successful creation of a new patch.
2642 Returns 0 on successful creation of a new patch.
2643 """
2643 """
2644 opts = pycompat.byteskwargs(opts)
2644 opts = pycompat.byteskwargs(opts)
2645 msg = cmdutil.logmessage(ui, opts)
2645 msg = cmdutil.logmessage(ui, opts)
2646 q = repo.mq
2646 q = repo.mq
2647 opts['msg'] = msg
2647 opts['msg'] = msg
2648 setupheaderopts(ui, opts)
2648 setupheaderopts(ui, opts)
2649 q.new(repo, patch, *args, **pycompat.strkwargs(opts))
2649 q.new(repo, patch, *args, **pycompat.strkwargs(opts))
2650 q.savedirty()
2650 q.savedirty()
2651 return 0
2651 return 0
2652
2652
2653 @command("^qrefresh",
2653 @command("^qrefresh",
2654 [('e', 'edit', None, _('invoke editor on commit messages')),
2654 [('e', 'edit', None, _('invoke editor on commit messages')),
2655 ('g', 'git', None, _('use git extended diff format')),
2655 ('g', 'git', None, _('use git extended diff format')),
2656 ('s', 'short', None,
2656 ('s', 'short', None,
2657 _('refresh only files already in the patch and specified files')),
2657 _('refresh only files already in the patch and specified files')),
2658 ('U', 'currentuser', None,
2658 ('U', 'currentuser', None,
2659 _('add/update author field in patch with current user')),
2659 _('add/update author field in patch with current user')),
2660 ('u', 'user', '',
2660 ('u', 'user', '',
2661 _('add/update author field in patch with given user'), _('USER')),
2661 _('add/update author field in patch with given user'), _('USER')),
2662 ('D', 'currentdate', None,
2662 ('D', 'currentdate', None,
2663 _('add/update date field in patch with current date')),
2663 _('add/update date field in patch with current date')),
2664 ('d', 'date', '',
2664 ('d', 'date', '',
2665 _('add/update date field in patch with given date'), _('DATE'))
2665 _('add/update date field in patch with given date'), _('DATE'))
2666 ] + cmdutil.walkopts + cmdutil.commitopts,
2666 ] + cmdutil.walkopts + cmdutil.commitopts,
2667 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'),
2667 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'),
2668 inferrepo=True)
2668 inferrepo=True)
2669 def refresh(ui, repo, *pats, **opts):
2669 def refresh(ui, repo, *pats, **opts):
2670 """update the current patch
2670 """update the current patch
2671
2671
2672 If any file patterns are provided, the refreshed patch will
2672 If any file patterns are provided, the refreshed patch will
2673 contain only the modifications that match those patterns; the
2673 contain only the modifications that match those patterns; the
2674 remaining modifications will remain in the working directory.
2674 remaining modifications will remain in the working directory.
2675
2675
2676 If -s/--short is specified, files currently included in the patch
2676 If -s/--short is specified, files currently included in the patch
2677 will be refreshed just like matched files and remain in the patch.
2677 will be refreshed just like matched files and remain in the patch.
2678
2678
2679 If -e/--edit is specified, Mercurial will start your configured editor for
2679 If -e/--edit is specified, Mercurial will start your configured editor for
2680 you to enter a message. In case qrefresh fails, you will find a backup of
2680 you to enter a message. In case qrefresh fails, you will find a backup of
2681 your message in ``.hg/last-message.txt``.
2681 your message in ``.hg/last-message.txt``.
2682
2682
2683 hg add/remove/copy/rename work as usual, though you might want to
2683 hg add/remove/copy/rename work as usual, though you might want to
2684 use git-style patches (-g/--git or [diff] git=1) to track copies
2684 use git-style patches (-g/--git or [diff] git=1) to track copies
2685 and renames. See the diffs help topic for more information on the
2685 and renames. See the diffs help topic for more information on the
2686 git diff format.
2686 git diff format.
2687
2687
2688 Returns 0 on success.
2688 Returns 0 on success.
2689 """
2689 """
2690 opts = pycompat.byteskwargs(opts)
2690 opts = pycompat.byteskwargs(opts)
2691 q = repo.mq
2691 q = repo.mq
2692 message = cmdutil.logmessage(ui, opts)
2692 message = cmdutil.logmessage(ui, opts)
2693 setupheaderopts(ui, opts)
2693 setupheaderopts(ui, opts)
2694 with repo.wlock():
2694 with repo.wlock():
2695 ret = q.refresh(repo, pats, msg=message, **pycompat.strkwargs(opts))
2695 ret = q.refresh(repo, pats, msg=message, **pycompat.strkwargs(opts))
2696 q.savedirty()
2696 q.savedirty()
2697 return ret
2697 return ret
2698
2698
2699 @command("^qdiff",
2699 @command("^qdiff",
2700 cmdutil.diffopts + cmdutil.diffopts2 + cmdutil.walkopts,
2700 cmdutil.diffopts + cmdutil.diffopts2 + cmdutil.walkopts,
2701 _('hg qdiff [OPTION]... [FILE]...'),
2701 _('hg qdiff [OPTION]... [FILE]...'),
2702 inferrepo=True)
2702 inferrepo=True)
2703 def diff(ui, repo, *pats, **opts):
2703 def diff(ui, repo, *pats, **opts):
2704 """diff of the current patch and subsequent modifications
2704 """diff of the current patch and subsequent modifications
2705
2705
2706 Shows a diff which includes the current patch as well as any
2706 Shows a diff which includes the current patch as well as any
2707 changes which have been made in the working directory since the
2707 changes which have been made in the working directory since the
2708 last refresh (thus showing what the current patch would become
2708 last refresh (thus showing what the current patch would become
2709 after a qrefresh).
2709 after a qrefresh).
2710
2710
2711 Use :hg:`diff` if you only want to see the changes made since the
2711 Use :hg:`diff` if you only want to see the changes made since the
2712 last qrefresh, or :hg:`export qtip` if you want to see changes
2712 last qrefresh, or :hg:`export qtip` if you want to see changes
2713 made by the current patch without including changes made since the
2713 made by the current patch without including changes made since the
2714 qrefresh.
2714 qrefresh.
2715
2715
2716 Returns 0 on success.
2716 Returns 0 on success.
2717 """
2717 """
2718 ui.pager('qdiff')
2718 ui.pager('qdiff')
2719 repo.mq.diff(repo, pats, pycompat.byteskwargs(opts))
2719 repo.mq.diff(repo, pats, pycompat.byteskwargs(opts))
2720 return 0
2720 return 0
2721
2721
2722 @command('qfold',
2722 @command('qfold',
2723 [('e', 'edit', None, _('invoke editor on commit messages')),
2723 [('e', 'edit', None, _('invoke editor on commit messages')),
2724 ('k', 'keep', None, _('keep folded patch files')),
2724 ('k', 'keep', None, _('keep folded patch files')),
2725 ] + cmdutil.commitopts,
2725 ] + cmdutil.commitopts,
2726 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'))
2726 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'))
2727 def fold(ui, repo, *files, **opts):
2727 def fold(ui, repo, *files, **opts):
2728 """fold the named patches into the current patch
2728 """fold the named patches into the current patch
2729
2729
2730 Patches must not yet be applied. Each patch will be successively
2730 Patches must not yet be applied. Each patch will be successively
2731 applied to the current patch in the order given. If all the
2731 applied to the current patch in the order given. If all the
2732 patches apply successfully, the current patch will be refreshed
2732 patches apply successfully, the current patch will be refreshed
2733 with the new cumulative patch, and the folded patches will be
2733 with the new cumulative patch, and the folded patches will be
2734 deleted. With -k/--keep, the folded patch files will not be
2734 deleted. With -k/--keep, the folded patch files will not be
2735 removed afterwards.
2735 removed afterwards.
2736
2736
2737 The header for each folded patch will be concatenated with the
2737 The header for each folded patch will be concatenated with the
2738 current patch header, separated by a line of ``* * *``.
2738 current patch header, separated by a line of ``* * *``.
2739
2739
2740 Returns 0 on success."""
2740 Returns 0 on success."""
2741 opts = pycompat.byteskwargs(opts)
2741 opts = pycompat.byteskwargs(opts)
2742 q = repo.mq
2742 q = repo.mq
2743 if not files:
2743 if not files:
2744 raise error.Abort(_('qfold requires at least one patch name'))
2744 raise error.Abort(_('qfold requires at least one patch name'))
2745 if not q.checktoppatch(repo)[0]:
2745 if not q.checktoppatch(repo)[0]:
2746 raise error.Abort(_('no patches applied'))
2746 raise error.Abort(_('no patches applied'))
2747 q.checklocalchanges(repo)
2747 q.checklocalchanges(repo)
2748
2748
2749 message = cmdutil.logmessage(ui, opts)
2749 message = cmdutil.logmessage(ui, opts)
2750
2750
2751 parent = q.lookup('qtip')
2751 parent = q.lookup('qtip')
2752 patches = []
2752 patches = []
2753 messages = []
2753 messages = []
2754 for f in files:
2754 for f in files:
2755 p = q.lookup(f)
2755 p = q.lookup(f)
2756 if p in patches or p == parent:
2756 if p in patches or p == parent:
2757 ui.warn(_('skipping already folded patch %s\n') % p)
2757 ui.warn(_('skipping already folded patch %s\n') % p)
2758 if q.isapplied(p):
2758 if q.isapplied(p):
2759 raise error.Abort(_('qfold cannot fold already applied patch %s')
2759 raise error.Abort(_('qfold cannot fold already applied patch %s')
2760 % p)
2760 % p)
2761 patches.append(p)
2761 patches.append(p)
2762
2762
2763 for p in patches:
2763 for p in patches:
2764 if not message:
2764 if not message:
2765 ph = patchheader(q.join(p), q.plainmode)
2765 ph = patchheader(q.join(p), q.plainmode)
2766 if ph.message:
2766 if ph.message:
2767 messages.append(ph.message)
2767 messages.append(ph.message)
2768 pf = q.join(p)
2768 pf = q.join(p)
2769 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2769 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2770 if not patchsuccess:
2770 if not patchsuccess:
2771 raise error.Abort(_('error folding patch %s') % p)
2771 raise error.Abort(_('error folding patch %s') % p)
2772
2772
2773 if not message:
2773 if not message:
2774 ph = patchheader(q.join(parent), q.plainmode)
2774 ph = patchheader(q.join(parent), q.plainmode)
2775 message = ph.message
2775 message = ph.message
2776 for msg in messages:
2776 for msg in messages:
2777 if msg:
2777 if msg:
2778 if message:
2778 if message:
2779 message.append('* * *')
2779 message.append('* * *')
2780 message.extend(msg)
2780 message.extend(msg)
2781 message = '\n'.join(message)
2781 message = '\n'.join(message)
2782
2782
2783 diffopts = q.patchopts(q.diffopts(), *patches)
2783 diffopts = q.patchopts(q.diffopts(), *patches)
2784 with repo.wlock():
2784 with repo.wlock():
2785 q.refresh(repo, msg=message, git=diffopts.git, edit=opts.get('edit'),
2785 q.refresh(repo, msg=message, git=diffopts.git, edit=opts.get('edit'),
2786 editform='mq.qfold')
2786 editform='mq.qfold')
2787 q.delete(repo, patches, opts)
2787 q.delete(repo, patches, opts)
2788 q.savedirty()
2788 q.savedirty()
2789
2789
2790 @command("qgoto",
2790 @command("qgoto",
2791 [('', 'keep-changes', None,
2791 [('', 'keep-changes', None,
2792 _('tolerate non-conflicting local changes')),
2792 _('tolerate non-conflicting local changes')),
2793 ('f', 'force', None, _('overwrite any local changes')),
2793 ('f', 'force', None, _('overwrite any local changes')),
2794 ('', 'no-backup', None, _('do not save backup copies of files'))],
2794 ('', 'no-backup', None, _('do not save backup copies of files'))],
2795 _('hg qgoto [OPTION]... PATCH'))
2795 _('hg qgoto [OPTION]... PATCH'))
2796 def goto(ui, repo, patch, **opts):
2796 def goto(ui, repo, patch, **opts):
2797 '''push or pop patches until named patch is at top of stack
2797 '''push or pop patches until named patch is at top of stack
2798
2798
2799 Returns 0 on success.'''
2799 Returns 0 on success.'''
2800 opts = pycompat.byteskwargs(opts)
2800 opts = pycompat.byteskwargs(opts)
2801 opts = fixkeepchangesopts(ui, opts)
2801 opts = fixkeepchangesopts(ui, opts)
2802 q = repo.mq
2802 q = repo.mq
2803 patch = q.lookup(patch)
2803 patch = q.lookup(patch)
2804 nobackup = opts.get('no_backup')
2804 nobackup = opts.get('no_backup')
2805 keepchanges = opts.get('keep_changes')
2805 keepchanges = opts.get('keep_changes')
2806 if q.isapplied(patch):
2806 if q.isapplied(patch):
2807 ret = q.pop(repo, patch, force=opts.get('force'), nobackup=nobackup,
2807 ret = q.pop(repo, patch, force=opts.get('force'), nobackup=nobackup,
2808 keepchanges=keepchanges)
2808 keepchanges=keepchanges)
2809 else:
2809 else:
2810 ret = q.push(repo, patch, force=opts.get('force'), nobackup=nobackup,
2810 ret = q.push(repo, patch, force=opts.get('force'), nobackup=nobackup,
2811 keepchanges=keepchanges)
2811 keepchanges=keepchanges)
2812 q.savedirty()
2812 q.savedirty()
2813 return ret
2813 return ret
2814
2814
2815 @command("qguard",
2815 @command("qguard",
2816 [('l', 'list', None, _('list all patches and guards')),
2816 [('l', 'list', None, _('list all patches and guards')),
2817 ('n', 'none', None, _('drop all guards'))],
2817 ('n', 'none', None, _('drop all guards'))],
2818 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'))
2818 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'))
2819 def guard(ui, repo, *args, **opts):
2819 def guard(ui, repo, *args, **opts):
2820 '''set or print guards for a patch
2820 '''set or print guards for a patch
2821
2821
2822 Guards control whether a patch can be pushed. A patch with no
2822 Guards control whether a patch can be pushed. A patch with no
2823 guards is always pushed. A patch with a positive guard ("+foo") is
2823 guards is always pushed. A patch with a positive guard ("+foo") is
2824 pushed only if the :hg:`qselect` command has activated it. A patch with
2824 pushed only if the :hg:`qselect` command has activated it. A patch with
2825 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
2825 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
2826 has activated it.
2826 has activated it.
2827
2827
2828 With no arguments, print the currently active guards.
2828 With no arguments, print the currently active guards.
2829 With arguments, set guards for the named patch.
2829 With arguments, set guards for the named patch.
2830
2830
2831 .. note::
2831 .. note::
2832
2832
2833 Specifying negative guards now requires '--'.
2833 Specifying negative guards now requires '--'.
2834
2834
2835 To set guards on another patch::
2835 To set guards on another patch::
2836
2836
2837 hg qguard other.patch -- +2.6.17 -stable
2837 hg qguard other.patch -- +2.6.17 -stable
2838
2838
2839 Returns 0 on success.
2839 Returns 0 on success.
2840 '''
2840 '''
2841 def status(idx):
2841 def status(idx):
2842 guards = q.seriesguards[idx] or ['unguarded']
2842 guards = q.seriesguards[idx] or ['unguarded']
2843 if q.series[idx] in applied:
2843 if q.series[idx] in applied:
2844 state = 'applied'
2844 state = 'applied'
2845 elif q.pushable(idx)[0]:
2845 elif q.pushable(idx)[0]:
2846 state = 'unapplied'
2846 state = 'unapplied'
2847 else:
2847 else:
2848 state = 'guarded'
2848 state = 'guarded'
2849 label = 'qguard.patch qguard.%s qseries.%s' % (state, state)
2849 label = 'qguard.patch qguard.%s qseries.%s' % (state, state)
2850 ui.write('%s: ' % ui.label(q.series[idx], label))
2850 ui.write('%s: ' % ui.label(q.series[idx], label))
2851
2851
2852 for i, guard in enumerate(guards):
2852 for i, guard in enumerate(guards):
2853 if guard.startswith('+'):
2853 if guard.startswith('+'):
2854 ui.write(guard, label='qguard.positive')
2854 ui.write(guard, label='qguard.positive')
2855 elif guard.startswith('-'):
2855 elif guard.startswith('-'):
2856 ui.write(guard, label='qguard.negative')
2856 ui.write(guard, label='qguard.negative')
2857 else:
2857 else:
2858 ui.write(guard, label='qguard.unguarded')
2858 ui.write(guard, label='qguard.unguarded')
2859 if i != len(guards) - 1:
2859 if i != len(guards) - 1:
2860 ui.write(' ')
2860 ui.write(' ')
2861 ui.write('\n')
2861 ui.write('\n')
2862 q = repo.mq
2862 q = repo.mq
2863 applied = set(p.name for p in q.applied)
2863 applied = set(p.name for p in q.applied)
2864 patch = None
2864 patch = None
2865 args = list(args)
2865 args = list(args)
2866 if opts.get(r'list'):
2866 if opts.get(r'list'):
2867 if args or opts.get('none'):
2867 if args or opts.get('none'):
2868 raise error.Abort(_('cannot mix -l/--list with options or '
2868 raise error.Abort(_('cannot mix -l/--list with options or '
2869 'arguments'))
2869 'arguments'))
2870 for i in xrange(len(q.series)):
2870 for i in xrange(len(q.series)):
2871 status(i)
2871 status(i)
2872 return
2872 return
2873 if not args or args[0][0:1] in '-+':
2873 if not args or args[0][0:1] in '-+':
2874 if not q.applied:
2874 if not q.applied:
2875 raise error.Abort(_('no patches applied'))
2875 raise error.Abort(_('no patches applied'))
2876 patch = q.applied[-1].name
2876 patch = q.applied[-1].name
2877 if patch is None and args[0][0:1] not in '-+':
2877 if patch is None and args[0][0:1] not in '-+':
2878 patch = args.pop(0)
2878 patch = args.pop(0)
2879 if patch is None:
2879 if patch is None:
2880 raise error.Abort(_('no patch to work with'))
2880 raise error.Abort(_('no patch to work with'))
2881 if args or opts.get('none'):
2881 if args or opts.get('none'):
2882 idx = q.findseries(patch)
2882 idx = q.findseries(patch)
2883 if idx is None:
2883 if idx is None:
2884 raise error.Abort(_('no patch named %s') % patch)
2884 raise error.Abort(_('no patch named %s') % patch)
2885 q.setguards(idx, args)
2885 q.setguards(idx, args)
2886 q.savedirty()
2886 q.savedirty()
2887 else:
2887 else:
2888 status(q.series.index(q.lookup(patch)))
2888 status(q.series.index(q.lookup(patch)))
2889
2889
2890 @command("qheader", [], _('hg qheader [PATCH]'))
2890 @command("qheader", [], _('hg qheader [PATCH]'))
2891 def header(ui, repo, patch=None):
2891 def header(ui, repo, patch=None):
2892 """print the header of the topmost or specified patch
2892 """print the header of the topmost or specified patch
2893
2893
2894 Returns 0 on success."""
2894 Returns 0 on success."""
2895 q = repo.mq
2895 q = repo.mq
2896
2896
2897 if patch:
2897 if patch:
2898 patch = q.lookup(patch)
2898 patch = q.lookup(patch)
2899 else:
2899 else:
2900 if not q.applied:
2900 if not q.applied:
2901 ui.write(_('no patches applied\n'))
2901 ui.write(_('no patches applied\n'))
2902 return 1
2902 return 1
2903 patch = q.lookup('qtip')
2903 patch = q.lookup('qtip')
2904 ph = patchheader(q.join(patch), q.plainmode)
2904 ph = patchheader(q.join(patch), q.plainmode)
2905
2905
2906 ui.write('\n'.join(ph.message) + '\n')
2906 ui.write('\n'.join(ph.message) + '\n')
2907
2907
2908 def lastsavename(path):
2908 def lastsavename(path):
2909 (directory, base) = os.path.split(path)
2909 (directory, base) = os.path.split(path)
2910 names = os.listdir(directory)
2910 names = os.listdir(directory)
2911 namere = re.compile("%s.([0-9]+)" % base)
2911 namere = re.compile("%s.([0-9]+)" % base)
2912 maxindex = None
2912 maxindex = None
2913 maxname = None
2913 maxname = None
2914 for f in names:
2914 for f in names:
2915 m = namere.match(f)
2915 m = namere.match(f)
2916 if m:
2916 if m:
2917 index = int(m.group(1))
2917 index = int(m.group(1))
2918 if maxindex is None or index > maxindex:
2918 if maxindex is None or index > maxindex:
2919 maxindex = index
2919 maxindex = index
2920 maxname = f
2920 maxname = f
2921 if maxname:
2921 if maxname:
2922 return (os.path.join(directory, maxname), maxindex)
2922 return (os.path.join(directory, maxname), maxindex)
2923 return (None, None)
2923 return (None, None)
2924
2924
2925 def savename(path):
2925 def savename(path):
2926 (last, index) = lastsavename(path)
2926 (last, index) = lastsavename(path)
2927 if last is None:
2927 if last is None:
2928 index = 0
2928 index = 0
2929 newpath = path + ".%d" % (index + 1)
2929 newpath = path + ".%d" % (index + 1)
2930 return newpath
2930 return newpath
2931
2931
2932 @command("^qpush",
2932 @command("^qpush",
2933 [('', 'keep-changes', None,
2933 [('', 'keep-changes', None,
2934 _('tolerate non-conflicting local changes')),
2934 _('tolerate non-conflicting local changes')),
2935 ('f', 'force', None, _('apply on top of local changes')),
2935 ('f', 'force', None, _('apply on top of local changes')),
2936 ('e', 'exact', None,
2936 ('e', 'exact', None,
2937 _('apply the target patch to its recorded parent')),
2937 _('apply the target patch to its recorded parent')),
2938 ('l', 'list', None, _('list patch name in commit text')),
2938 ('l', 'list', None, _('list patch name in commit text')),
2939 ('a', 'all', None, _('apply all patches')),
2939 ('a', 'all', None, _('apply all patches')),
2940 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2940 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2941 ('n', 'name', '',
2941 ('n', 'name', '',
2942 _('merge queue name (DEPRECATED)'), _('NAME')),
2942 _('merge queue name (DEPRECATED)'), _('NAME')),
2943 ('', 'move', None,
2943 ('', 'move', None,
2944 _('reorder patch series and apply only the patch')),
2944 _('reorder patch series and apply only the patch')),
2945 ('', 'no-backup', None, _('do not save backup copies of files'))],
2945 ('', 'no-backup', None, _('do not save backup copies of files'))],
2946 _('hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'))
2946 _('hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'))
2947 def push(ui, repo, patch=None, **opts):
2947 def push(ui, repo, patch=None, **opts):
2948 """push the next patch onto the stack
2948 """push the next patch onto the stack
2949
2949
2950 By default, abort if the working directory contains uncommitted
2950 By default, abort if the working directory contains uncommitted
2951 changes. With --keep-changes, abort only if the uncommitted files
2951 changes. With --keep-changes, abort only if the uncommitted files
2952 overlap with patched files. With -f/--force, backup and patch over
2952 overlap with patched files. With -f/--force, backup and patch over
2953 uncommitted changes.
2953 uncommitted changes.
2954
2954
2955 Return 0 on success.
2955 Return 0 on success.
2956 """
2956 """
2957 q = repo.mq
2957 q = repo.mq
2958 mergeq = None
2958 mergeq = None
2959
2959
2960 opts = pycompat.byteskwargs(opts)
2960 opts = pycompat.byteskwargs(opts)
2961 opts = fixkeepchangesopts(ui, opts)
2961 opts = fixkeepchangesopts(ui, opts)
2962 if opts.get('merge'):
2962 if opts.get('merge'):
2963 if opts.get('name'):
2963 if opts.get('name'):
2964 newpath = repo.vfs.join(opts.get('name'))
2964 newpath = repo.vfs.join(opts.get('name'))
2965 else:
2965 else:
2966 newpath, i = lastsavename(q.path)
2966 newpath, i = lastsavename(q.path)
2967 if not newpath:
2967 if not newpath:
2968 ui.warn(_("no saved queues found, please use -n\n"))
2968 ui.warn(_("no saved queues found, please use -n\n"))
2969 return 1
2969 return 1
2970 mergeq = queue(ui, repo.baseui, repo.path, newpath)
2970 mergeq = queue(ui, repo.baseui, repo.path, newpath)
2971 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2971 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2972 ret = q.push(repo, patch, force=opts.get('force'), list=opts.get('list'),
2972 ret = q.push(repo, patch, force=opts.get('force'), list=opts.get('list'),
2973 mergeq=mergeq, all=opts.get('all'), move=opts.get('move'),
2973 mergeq=mergeq, all=opts.get('all'), move=opts.get('move'),
2974 exact=opts.get('exact'), nobackup=opts.get('no_backup'),
2974 exact=opts.get('exact'), nobackup=opts.get('no_backup'),
2975 keepchanges=opts.get('keep_changes'))
2975 keepchanges=opts.get('keep_changes'))
2976 return ret
2976 return ret
2977
2977
2978 @command("^qpop",
2978 @command("^qpop",
2979 [('a', 'all', None, _('pop all patches')),
2979 [('a', 'all', None, _('pop all patches')),
2980 ('n', 'name', '',
2980 ('n', 'name', '',
2981 _('queue name to pop (DEPRECATED)'), _('NAME')),
2981 _('queue name to pop (DEPRECATED)'), _('NAME')),
2982 ('', 'keep-changes', None,
2982 ('', 'keep-changes', None,
2983 _('tolerate non-conflicting local changes')),
2983 _('tolerate non-conflicting local changes')),
2984 ('f', 'force', None, _('forget any local changes to patched files')),
2984 ('f', 'force', None, _('forget any local changes to patched files')),
2985 ('', 'no-backup', None, _('do not save backup copies of files'))],
2985 ('', 'no-backup', None, _('do not save backup copies of files'))],
2986 _('hg qpop [-a] [-f] [PATCH | INDEX]'))
2986 _('hg qpop [-a] [-f] [PATCH | INDEX]'))
2987 def pop(ui, repo, patch=None, **opts):
2987 def pop(ui, repo, patch=None, **opts):
2988 """pop the current patch off the stack
2988 """pop the current patch off the stack
2989
2989
2990 Without argument, pops off the top of the patch stack. If given a
2990 Without argument, pops off the top of the patch stack. If given a
2991 patch name, keeps popping off patches until the named patch is at
2991 patch name, keeps popping off patches until the named patch is at
2992 the top of the stack.
2992 the top of the stack.
2993
2993
2994 By default, abort if the working directory contains uncommitted
2994 By default, abort if the working directory contains uncommitted
2995 changes. With --keep-changes, abort only if the uncommitted files
2995 changes. With --keep-changes, abort only if the uncommitted files
2996 overlap with patched files. With -f/--force, backup and discard
2996 overlap with patched files. With -f/--force, backup and discard
2997 changes made to such files.
2997 changes made to such files.
2998
2998
2999 Return 0 on success.
2999 Return 0 on success.
3000 """
3000 """
3001 opts = pycompat.byteskwargs(opts)
3001 opts = pycompat.byteskwargs(opts)
3002 opts = fixkeepchangesopts(ui, opts)
3002 opts = fixkeepchangesopts(ui, opts)
3003 localupdate = True
3003 localupdate = True
3004 if opts.get('name'):
3004 if opts.get('name'):
3005 q = queue(ui, repo.baseui, repo.path, repo.vfs.join(opts.get('name')))
3005 q = queue(ui, repo.baseui, repo.path, repo.vfs.join(opts.get('name')))
3006 ui.warn(_('using patch queue: %s\n') % q.path)
3006 ui.warn(_('using patch queue: %s\n') % q.path)
3007 localupdate = False
3007 localupdate = False
3008 else:
3008 else:
3009 q = repo.mq
3009 q = repo.mq
3010 ret = q.pop(repo, patch, force=opts.get('force'), update=localupdate,
3010 ret = q.pop(repo, patch, force=opts.get('force'), update=localupdate,
3011 all=opts.get('all'), nobackup=opts.get('no_backup'),
3011 all=opts.get('all'), nobackup=opts.get('no_backup'),
3012 keepchanges=opts.get('keep_changes'))
3012 keepchanges=opts.get('keep_changes'))
3013 q.savedirty()
3013 q.savedirty()
3014 return ret
3014 return ret
3015
3015
3016 @command("qrename|qmv", [], _('hg qrename PATCH1 [PATCH2]'))
3016 @command("qrename|qmv", [], _('hg qrename PATCH1 [PATCH2]'))
3017 def rename(ui, repo, patch, name=None, **opts):
3017 def rename(ui, repo, patch, name=None, **opts):
3018 """rename a patch
3018 """rename a patch
3019
3019
3020 With one argument, renames the current patch to PATCH1.
3020 With one argument, renames the current patch to PATCH1.
3021 With two arguments, renames PATCH1 to PATCH2.
3021 With two arguments, renames PATCH1 to PATCH2.
3022
3022
3023 Returns 0 on success."""
3023 Returns 0 on success."""
3024 q = repo.mq
3024 q = repo.mq
3025 if not name:
3025 if not name:
3026 name = patch
3026 name = patch
3027 patch = None
3027 patch = None
3028
3028
3029 if patch:
3029 if patch:
3030 patch = q.lookup(patch)
3030 patch = q.lookup(patch)
3031 else:
3031 else:
3032 if not q.applied:
3032 if not q.applied:
3033 ui.write(_('no patches applied\n'))
3033 ui.write(_('no patches applied\n'))
3034 return
3034 return
3035 patch = q.lookup('qtip')
3035 patch = q.lookup('qtip')
3036 absdest = q.join(name)
3036 absdest = q.join(name)
3037 if os.path.isdir(absdest):
3037 if os.path.isdir(absdest):
3038 name = normname(os.path.join(name, os.path.basename(patch)))
3038 name = normname(os.path.join(name, os.path.basename(patch)))
3039 absdest = q.join(name)
3039 absdest = q.join(name)
3040 q.checkpatchname(name)
3040 q.checkpatchname(name)
3041
3041
3042 ui.note(_('renaming %s to %s\n') % (patch, name))
3042 ui.note(_('renaming %s to %s\n') % (patch, name))
3043 i = q.findseries(patch)
3043 i = q.findseries(patch)
3044 guards = q.guard_re.findall(q.fullseries[i])
3044 guards = q.guard_re.findall(q.fullseries[i])
3045 q.fullseries[i] = name + ''.join([' #' + g for g in guards])
3045 q.fullseries[i] = name + ''.join([' #' + g for g in guards])
3046 q.parseseries()
3046 q.parseseries()
3047 q.seriesdirty = True
3047 q.seriesdirty = True
3048
3048
3049 info = q.isapplied(patch)
3049 info = q.isapplied(patch)
3050 if info:
3050 if info:
3051 q.applied[info[0]] = statusentry(info[1], name)
3051 q.applied[info[0]] = statusentry(info[1], name)
3052 q.applieddirty = True
3052 q.applieddirty = True
3053
3053
3054 destdir = os.path.dirname(absdest)
3054 destdir = os.path.dirname(absdest)
3055 if not os.path.isdir(destdir):
3055 if not os.path.isdir(destdir):
3056 os.makedirs(destdir)
3056 os.makedirs(destdir)
3057 util.rename(q.join(patch), absdest)
3057 util.rename(q.join(patch), absdest)
3058 r = q.qrepo()
3058 r = q.qrepo()
3059 if r and patch in r.dirstate:
3059 if r and patch in r.dirstate:
3060 wctx = r[None]
3060 wctx = r[None]
3061 with r.wlock():
3061 with r.wlock():
3062 if r.dirstate[patch] == 'a':
3062 if r.dirstate[patch] == 'a':
3063 r.dirstate.drop(patch)
3063 r.dirstate.drop(patch)
3064 r.dirstate.add(name)
3064 r.dirstate.add(name)
3065 else:
3065 else:
3066 wctx.copy(patch, name)
3066 wctx.copy(patch, name)
3067 wctx.forget([patch])
3067 wctx.forget([patch])
3068
3068
3069 q.savedirty()
3069 q.savedirty()
3070
3070
3071 @command("qrestore",
3071 @command("qrestore",
3072 [('d', 'delete', None, _('delete save entry')),
3072 [('d', 'delete', None, _('delete save entry')),
3073 ('u', 'update', None, _('update queue working directory'))],
3073 ('u', 'update', None, _('update queue working directory'))],
3074 _('hg qrestore [-d] [-u] REV'))
3074 _('hg qrestore [-d] [-u] REV'))
3075 def restore(ui, repo, rev, **opts):
3075 def restore(ui, repo, rev, **opts):
3076 """restore the queue state saved by a revision (DEPRECATED)
3076 """restore the queue state saved by a revision (DEPRECATED)
3077
3077
3078 This command is deprecated, use :hg:`rebase` instead."""
3078 This command is deprecated, use :hg:`rebase` instead."""
3079 rev = repo.lookup(rev)
3079 rev = repo.lookup(rev)
3080 q = repo.mq
3080 q = repo.mq
3081 q.restore(repo, rev, delete=opts.get(r'delete'),
3081 q.restore(repo, rev, delete=opts.get(r'delete'),
3082 qupdate=opts.get(r'update'))
3082 qupdate=opts.get(r'update'))
3083 q.savedirty()
3083 q.savedirty()
3084 return 0
3084 return 0
3085
3085
3086 @command("qsave",
3086 @command("qsave",
3087 [('c', 'copy', None, _('copy patch directory')),
3087 [('c', 'copy', None, _('copy patch directory')),
3088 ('n', 'name', '',
3088 ('n', 'name', '',
3089 _('copy directory name'), _('NAME')),
3089 _('copy directory name'), _('NAME')),
3090 ('e', 'empty', None, _('clear queue status file')),
3090 ('e', 'empty', None, _('clear queue status file')),
3091 ('f', 'force', None, _('force copy'))] + cmdutil.commitopts,
3091 ('f', 'force', None, _('force copy'))] + cmdutil.commitopts,
3092 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'))
3092 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'))
3093 def save(ui, repo, **opts):
3093 def save(ui, repo, **opts):
3094 """save current queue state (DEPRECATED)
3094 """save current queue state (DEPRECATED)
3095
3095
3096 This command is deprecated, use :hg:`rebase` instead."""
3096 This command is deprecated, use :hg:`rebase` instead."""
3097 q = repo.mq
3097 q = repo.mq
3098 opts = pycompat.byteskwargs(opts)
3098 opts = pycompat.byteskwargs(opts)
3099 message = cmdutil.logmessage(ui, opts)
3099 message = cmdutil.logmessage(ui, opts)
3100 ret = q.save(repo, msg=message)
3100 ret = q.save(repo, msg=message)
3101 if ret:
3101 if ret:
3102 return ret
3102 return ret
3103 q.savedirty() # save to .hg/patches before copying
3103 q.savedirty() # save to .hg/patches before copying
3104 if opts.get('copy'):
3104 if opts.get('copy'):
3105 path = q.path
3105 path = q.path
3106 if opts.get('name'):
3106 if opts.get('name'):
3107 newpath = os.path.join(q.basepath, opts.get('name'))
3107 newpath = os.path.join(q.basepath, opts.get('name'))
3108 if os.path.exists(newpath):
3108 if os.path.exists(newpath):
3109 if not os.path.isdir(newpath):
3109 if not os.path.isdir(newpath):
3110 raise error.Abort(_('destination %s exists and is not '
3110 raise error.Abort(_('destination %s exists and is not '
3111 'a directory') % newpath)
3111 'a directory') % newpath)
3112 if not opts.get('force'):
3112 if not opts.get('force'):
3113 raise error.Abort(_('destination %s exists, '
3113 raise error.Abort(_('destination %s exists, '
3114 'use -f to force') % newpath)
3114 'use -f to force') % newpath)
3115 else:
3115 else:
3116 newpath = savename(path)
3116 newpath = savename(path)
3117 ui.warn(_("copy %s to %s\n") % (path, newpath))
3117 ui.warn(_("copy %s to %s\n") % (path, newpath))
3118 util.copyfiles(path, newpath)
3118 util.copyfiles(path, newpath)
3119 if opts.get('empty'):
3119 if opts.get('empty'):
3120 del q.applied[:]
3120 del q.applied[:]
3121 q.applieddirty = True
3121 q.applieddirty = True
3122 q.savedirty()
3122 q.savedirty()
3123 return 0
3123 return 0
3124
3124
3125
3125
3126 @command("qselect",
3126 @command("qselect",
3127 [('n', 'none', None, _('disable all guards')),
3127 [('n', 'none', None, _('disable all guards')),
3128 ('s', 'series', None, _('list all guards in series file')),
3128 ('s', 'series', None, _('list all guards in series file')),
3129 ('', 'pop', None, _('pop to before first guarded applied patch')),
3129 ('', 'pop', None, _('pop to before first guarded applied patch')),
3130 ('', 'reapply', None, _('pop, then reapply patches'))],
3130 ('', 'reapply', None, _('pop, then reapply patches'))],
3131 _('hg qselect [OPTION]... [GUARD]...'))
3131 _('hg qselect [OPTION]... [GUARD]...'))
3132 def select(ui, repo, *args, **opts):
3132 def select(ui, repo, *args, **opts):
3133 '''set or print guarded patches to push
3133 '''set or print guarded patches to push
3134
3134
3135 Use the :hg:`qguard` command to set or print guards on patch, then use
3135 Use the :hg:`qguard` command to set or print guards on patch, then use
3136 qselect to tell mq which guards to use. A patch will be pushed if
3136 qselect to tell mq which guards to use. A patch will be pushed if
3137 it has no guards or any positive guards match the currently
3137 it has no guards or any positive guards match the currently
3138 selected guard, but will not be pushed if any negative guards
3138 selected guard, but will not be pushed if any negative guards
3139 match the current guard. For example::
3139 match the current guard. For example::
3140
3140
3141 qguard foo.patch -- -stable (negative guard)
3141 qguard foo.patch -- -stable (negative guard)
3142 qguard bar.patch +stable (positive guard)
3142 qguard bar.patch +stable (positive guard)
3143 qselect stable
3143 qselect stable
3144
3144
3145 This activates the "stable" guard. mq will skip foo.patch (because
3145 This activates the "stable" guard. mq will skip foo.patch (because
3146 it has a negative match) but push bar.patch (because it has a
3146 it has a negative match) but push bar.patch (because it has a
3147 positive match).
3147 positive match).
3148
3148
3149 With no arguments, prints the currently active guards.
3149 With no arguments, prints the currently active guards.
3150 With one argument, sets the active guard.
3150 With one argument, sets the active guard.
3151
3151
3152 Use -n/--none to deactivate guards (no other arguments needed).
3152 Use -n/--none to deactivate guards (no other arguments needed).
3153 When no guards are active, patches with positive guards are
3153 When no guards are active, patches with positive guards are
3154 skipped and patches with negative guards are pushed.
3154 skipped and patches with negative guards are pushed.
3155
3155
3156 qselect can change the guards on applied patches. It does not pop
3156 qselect can change the guards on applied patches. It does not pop
3157 guarded patches by default. Use --pop to pop back to the last
3157 guarded patches by default. Use --pop to pop back to the last
3158 applied patch that is not guarded. Use --reapply (which implies
3158 applied patch that is not guarded. Use --reapply (which implies
3159 --pop) to push back to the current patch afterwards, but skip
3159 --pop) to push back to the current patch afterwards, but skip
3160 guarded patches.
3160 guarded patches.
3161
3161
3162 Use -s/--series to print a list of all guards in the series file
3162 Use -s/--series to print a list of all guards in the series file
3163 (no other arguments needed). Use -v for more information.
3163 (no other arguments needed). Use -v for more information.
3164
3164
3165 Returns 0 on success.'''
3165 Returns 0 on success.'''
3166
3166
3167 q = repo.mq
3167 q = repo.mq
3168 opts = pycompat.byteskwargs(opts)
3168 opts = pycompat.byteskwargs(opts)
3169 guards = q.active()
3169 guards = q.active()
3170 pushable = lambda i: q.pushable(q.applied[i].name)[0]
3170 pushable = lambda i: q.pushable(q.applied[i].name)[0]
3171 if args or opts.get('none'):
3171 if args or opts.get('none'):
3172 old_unapplied = q.unapplied(repo)
3172 old_unapplied = q.unapplied(repo)
3173 old_guarded = [i for i in xrange(len(q.applied)) if not pushable(i)]
3173 old_guarded = [i for i in xrange(len(q.applied)) if not pushable(i)]
3174 q.setactive(args)
3174 q.setactive(args)
3175 q.savedirty()
3175 q.savedirty()
3176 if not args:
3176 if not args:
3177 ui.status(_('guards deactivated\n'))
3177 ui.status(_('guards deactivated\n'))
3178 if not opts.get('pop') and not opts.get('reapply'):
3178 if not opts.get('pop') and not opts.get('reapply'):
3179 unapplied = q.unapplied(repo)
3179 unapplied = q.unapplied(repo)
3180 guarded = [i for i in xrange(len(q.applied)) if not pushable(i)]
3180 guarded = [i for i in xrange(len(q.applied)) if not pushable(i)]
3181 if len(unapplied) != len(old_unapplied):
3181 if len(unapplied) != len(old_unapplied):
3182 ui.status(_('number of unguarded, unapplied patches has '
3182 ui.status(_('number of unguarded, unapplied patches has '
3183 'changed from %d to %d\n') %
3183 'changed from %d to %d\n') %
3184 (len(old_unapplied), len(unapplied)))
3184 (len(old_unapplied), len(unapplied)))
3185 if len(guarded) != len(old_guarded):
3185 if len(guarded) != len(old_guarded):
3186 ui.status(_('number of guarded, applied patches has changed '
3186 ui.status(_('number of guarded, applied patches has changed '
3187 'from %d to %d\n') %
3187 'from %d to %d\n') %
3188 (len(old_guarded), len(guarded)))
3188 (len(old_guarded), len(guarded)))
3189 elif opts.get('series'):
3189 elif opts.get('series'):
3190 guards = {}
3190 guards = {}
3191 noguards = 0
3191 noguards = 0
3192 for gs in q.seriesguards:
3192 for gs in q.seriesguards:
3193 if not gs:
3193 if not gs:
3194 noguards += 1
3194 noguards += 1
3195 for g in gs:
3195 for g in gs:
3196 guards.setdefault(g, 0)
3196 guards.setdefault(g, 0)
3197 guards[g] += 1
3197 guards[g] += 1
3198 if ui.verbose:
3198 if ui.verbose:
3199 guards['NONE'] = noguards
3199 guards['NONE'] = noguards
3200 guards = list(guards.items())
3200 guards = list(guards.items())
3201 guards.sort(key=lambda x: x[0][1:])
3201 guards.sort(key=lambda x: x[0][1:])
3202 if guards:
3202 if guards:
3203 ui.note(_('guards in series file:\n'))
3203 ui.note(_('guards in series file:\n'))
3204 for guard, count in guards:
3204 for guard, count in guards:
3205 ui.note('%2d ' % count)
3205 ui.note('%2d ' % count)
3206 ui.write(guard, '\n')
3206 ui.write(guard, '\n')
3207 else:
3207 else:
3208 ui.note(_('no guards in series file\n'))
3208 ui.note(_('no guards in series file\n'))
3209 else:
3209 else:
3210 if guards:
3210 if guards:
3211 ui.note(_('active guards:\n'))
3211 ui.note(_('active guards:\n'))
3212 for g in guards:
3212 for g in guards:
3213 ui.write(g, '\n')
3213 ui.write(g, '\n')
3214 else:
3214 else:
3215 ui.write(_('no active guards\n'))
3215 ui.write(_('no active guards\n'))
3216 reapply = opts.get('reapply') and q.applied and q.applied[-1].name
3216 reapply = opts.get('reapply') and q.applied and q.applied[-1].name
3217 popped = False
3217 popped = False
3218 if opts.get('pop') or opts.get('reapply'):
3218 if opts.get('pop') or opts.get('reapply'):
3219 for i in xrange(len(q.applied)):
3219 for i in xrange(len(q.applied)):
3220 if not pushable(i):
3220 if not pushable(i):
3221 ui.status(_('popping guarded patches\n'))
3221 ui.status(_('popping guarded patches\n'))
3222 popped = True
3222 popped = True
3223 if i == 0:
3223 if i == 0:
3224 q.pop(repo, all=True)
3224 q.pop(repo, all=True)
3225 else:
3225 else:
3226 q.pop(repo, q.applied[i - 1].name)
3226 q.pop(repo, q.applied[i - 1].name)
3227 break
3227 break
3228 if popped:
3228 if popped:
3229 try:
3229 try:
3230 if reapply:
3230 if reapply:
3231 ui.status(_('reapplying unguarded patches\n'))
3231 ui.status(_('reapplying unguarded patches\n'))
3232 q.push(repo, reapply)
3232 q.push(repo, reapply)
3233 finally:
3233 finally:
3234 q.savedirty()
3234 q.savedirty()
3235
3235
3236 @command("qfinish",
3236 @command("qfinish",
3237 [('a', 'applied', None, _('finish all applied changesets'))],
3237 [('a', 'applied', None, _('finish all applied changesets'))],
3238 _('hg qfinish [-a] [REV]...'))
3238 _('hg qfinish [-a] [REV]...'))
3239 def finish(ui, repo, *revrange, **opts):
3239 def finish(ui, repo, *revrange, **opts):
3240 """move applied patches into repository history
3240 """move applied patches into repository history
3241
3241
3242 Finishes the specified revisions (corresponding to applied
3242 Finishes the specified revisions (corresponding to applied
3243 patches) by moving them out of mq control into regular repository
3243 patches) by moving them out of mq control into regular repository
3244 history.
3244 history.
3245
3245
3246 Accepts a revision range or the -a/--applied option. If --applied
3246 Accepts a revision range or the -a/--applied option. If --applied
3247 is specified, all applied mq revisions are removed from mq
3247 is specified, all applied mq revisions are removed from mq
3248 control. Otherwise, the given revisions must be at the base of the
3248 control. Otherwise, the given revisions must be at the base of the
3249 stack of applied patches.
3249 stack of applied patches.
3250
3250
3251 This can be especially useful if your changes have been applied to
3251 This can be especially useful if your changes have been applied to
3252 an upstream repository, or if you are about to push your changes
3252 an upstream repository, or if you are about to push your changes
3253 to upstream.
3253 to upstream.
3254
3254
3255 Returns 0 on success.
3255 Returns 0 on success.
3256 """
3256 """
3257 if not opts.get(r'applied') and not revrange:
3257 if not opts.get(r'applied') and not revrange:
3258 raise error.Abort(_('no revisions specified'))
3258 raise error.Abort(_('no revisions specified'))
3259 elif opts.get(r'applied'):
3259 elif opts.get(r'applied'):
3260 revrange = ('qbase::qtip',) + revrange
3260 revrange = ('qbase::qtip',) + revrange
3261
3261
3262 q = repo.mq
3262 q = repo.mq
3263 if not q.applied:
3263 if not q.applied:
3264 ui.status(_('no patches applied\n'))
3264 ui.status(_('no patches applied\n'))
3265 return 0
3265 return 0
3266
3266
3267 revs = scmutil.revrange(repo, revrange)
3267 revs = scmutil.revrange(repo, revrange)
3268 if repo['.'].rev() in revs and repo[None].files():
3268 if repo['.'].rev() in revs and repo[None].files():
3269 ui.warn(_('warning: uncommitted changes in the working directory\n'))
3269 ui.warn(_('warning: uncommitted changes in the working directory\n'))
3270 # queue.finish may changes phases but leave the responsibility to lock the
3270 # queue.finish may changes phases but leave the responsibility to lock the
3271 # repo to the caller to avoid deadlock with wlock. This command code is
3271 # repo to the caller to avoid deadlock with wlock. This command code is
3272 # responsibility for this locking.
3272 # responsibility for this locking.
3273 with repo.lock():
3273 with repo.lock():
3274 q.finish(repo, revs)
3274 q.finish(repo, revs)
3275 q.savedirty()
3275 q.savedirty()
3276 return 0
3276 return 0
3277
3277
3278 @command("qqueue",
3278 @command("qqueue",
3279 [('l', 'list', False, _('list all available queues')),
3279 [('l', 'list', False, _('list all available queues')),
3280 ('', 'active', False, _('print name of active queue')),
3280 ('', 'active', False, _('print name of active queue')),
3281 ('c', 'create', False, _('create new queue')),
3281 ('c', 'create', False, _('create new queue')),
3282 ('', 'rename', False, _('rename active queue')),
3282 ('', 'rename', False, _('rename active queue')),
3283 ('', 'delete', False, _('delete reference to queue')),
3283 ('', 'delete', False, _('delete reference to queue')),
3284 ('', 'purge', False, _('delete queue, and remove patch dir')),
3284 ('', 'purge', False, _('delete queue, and remove patch dir')),
3285 ],
3285 ],
3286 _('[OPTION] [QUEUE]'))
3286 _('[OPTION] [QUEUE]'))
3287 def qqueue(ui, repo, name=None, **opts):
3287 def qqueue(ui, repo, name=None, **opts):
3288 '''manage multiple patch queues
3288 '''manage multiple patch queues
3289
3289
3290 Supports switching between different patch queues, as well as creating
3290 Supports switching between different patch queues, as well as creating
3291 new patch queues and deleting existing ones.
3291 new patch queues and deleting existing ones.
3292
3292
3293 Omitting a queue name or specifying -l/--list will show you the registered
3293 Omitting a queue name or specifying -l/--list will show you the registered
3294 queues - by default the "normal" patches queue is registered. The currently
3294 queues - by default the "normal" patches queue is registered. The currently
3295 active queue will be marked with "(active)". Specifying --active will print
3295 active queue will be marked with "(active)". Specifying --active will print
3296 only the name of the active queue.
3296 only the name of the active queue.
3297
3297
3298 To create a new queue, use -c/--create. The queue is automatically made
3298 To create a new queue, use -c/--create. The queue is automatically made
3299 active, except in the case where there are applied patches from the
3299 active, except in the case where there are applied patches from the
3300 currently active queue in the repository. Then the queue will only be
3300 currently active queue in the repository. Then the queue will only be
3301 created and switching will fail.
3301 created and switching will fail.
3302
3302
3303 To delete an existing queue, use --delete. You cannot delete the currently
3303 To delete an existing queue, use --delete. You cannot delete the currently
3304 active queue.
3304 active queue.
3305
3305
3306 Returns 0 on success.
3306 Returns 0 on success.
3307 '''
3307 '''
3308 q = repo.mq
3308 q = repo.mq
3309 _defaultqueue = 'patches'
3309 _defaultqueue = 'patches'
3310 _allqueues = 'patches.queues'
3310 _allqueues = 'patches.queues'
3311 _activequeue = 'patches.queue'
3311 _activequeue = 'patches.queue'
3312
3312
3313 def _getcurrent():
3313 def _getcurrent():
3314 cur = os.path.basename(q.path)
3314 cur = os.path.basename(q.path)
3315 if cur.startswith('patches-'):
3315 if cur.startswith('patches-'):
3316 cur = cur[8:]
3316 cur = cur[8:]
3317 return cur
3317 return cur
3318
3318
3319 def _noqueues():
3319 def _noqueues():
3320 try:
3320 try:
3321 fh = repo.vfs(_allqueues, 'r')
3321 fh = repo.vfs(_allqueues, 'r')
3322 fh.close()
3322 fh.close()
3323 except IOError:
3323 except IOError:
3324 return True
3324 return True
3325
3325
3326 return False
3326 return False
3327
3327
3328 def _getqueues():
3328 def _getqueues():
3329 current = _getcurrent()
3329 current = _getcurrent()
3330
3330
3331 try:
3331 try:
3332 fh = repo.vfs(_allqueues, 'r')
3332 fh = repo.vfs(_allqueues, 'r')
3333 queues = [queue.strip() for queue in fh if queue.strip()]
3333 queues = [queue.strip() for queue in fh if queue.strip()]
3334 fh.close()
3334 fh.close()
3335 if current not in queues:
3335 if current not in queues:
3336 queues.append(current)
3336 queues.append(current)
3337 except IOError:
3337 except IOError:
3338 queues = [_defaultqueue]
3338 queues = [_defaultqueue]
3339
3339
3340 return sorted(queues)
3340 return sorted(queues)
3341
3341
3342 def _setactive(name):
3342 def _setactive(name):
3343 if q.applied:
3343 if q.applied:
3344 raise error.Abort(_('new queue created, but cannot make active '
3344 raise error.Abort(_('new queue created, but cannot make active '
3345 'as patches are applied'))
3345 'as patches are applied'))
3346 _setactivenocheck(name)
3346 _setactivenocheck(name)
3347
3347
3348 def _setactivenocheck(name):
3348 def _setactivenocheck(name):
3349 fh = repo.vfs(_activequeue, 'w')
3349 fh = repo.vfs(_activequeue, 'w')
3350 if name != 'patches':
3350 if name != 'patches':
3351 fh.write(name)
3351 fh.write(name)
3352 fh.close()
3352 fh.close()
3353
3353
3354 def _addqueue(name):
3354 def _addqueue(name):
3355 fh = repo.vfs(_allqueues, 'a')
3355 fh = repo.vfs(_allqueues, 'a')
3356 fh.write('%s\n' % (name,))
3356 fh.write('%s\n' % (name,))
3357 fh.close()
3357 fh.close()
3358
3358
3359 def _queuedir(name):
3359 def _queuedir(name):
3360 if name == 'patches':
3360 if name == 'patches':
3361 return repo.vfs.join('patches')
3361 return repo.vfs.join('patches')
3362 else:
3362 else:
3363 return repo.vfs.join('patches-' + name)
3363 return repo.vfs.join('patches-' + name)
3364
3364
3365 def _validname(name):
3365 def _validname(name):
3366 for n in name:
3366 for n in name:
3367 if n in ':\\/.':
3367 if n in ':\\/.':
3368 return False
3368 return False
3369 return True
3369 return True
3370
3370
3371 def _delete(name):
3371 def _delete(name):
3372 if name not in existing:
3372 if name not in existing:
3373 raise error.Abort(_('cannot delete queue that does not exist'))
3373 raise error.Abort(_('cannot delete queue that does not exist'))
3374
3374
3375 current = _getcurrent()
3375 current = _getcurrent()
3376
3376
3377 if name == current:
3377 if name == current:
3378 raise error.Abort(_('cannot delete currently active queue'))
3378 raise error.Abort(_('cannot delete currently active queue'))
3379
3379
3380 fh = repo.vfs('patches.queues.new', 'w')
3380 fh = repo.vfs('patches.queues.new', 'w')
3381 for queue in existing:
3381 for queue in existing:
3382 if queue == name:
3382 if queue == name:
3383 continue
3383 continue
3384 fh.write('%s\n' % (queue,))
3384 fh.write('%s\n' % (queue,))
3385 fh.close()
3385 fh.close()
3386 repo.vfs.rename('patches.queues.new', _allqueues)
3386 repo.vfs.rename('patches.queues.new', _allqueues)
3387
3387
3388 opts = pycompat.byteskwargs(opts)
3388 opts = pycompat.byteskwargs(opts)
3389 if not name or opts.get('list') or opts.get('active'):
3389 if not name or opts.get('list') or opts.get('active'):
3390 current = _getcurrent()
3390 current = _getcurrent()
3391 if opts.get('active'):
3391 if opts.get('active'):
3392 ui.write('%s\n' % (current,))
3392 ui.write('%s\n' % (current,))
3393 return
3393 return
3394 for queue in _getqueues():
3394 for queue in _getqueues():
3395 ui.write('%s' % (queue,))
3395 ui.write('%s' % (queue,))
3396 if queue == current and not ui.quiet:
3396 if queue == current and not ui.quiet:
3397 ui.write(_(' (active)\n'))
3397 ui.write(_(' (active)\n'))
3398 else:
3398 else:
3399 ui.write('\n')
3399 ui.write('\n')
3400 return
3400 return
3401
3401
3402 if not _validname(name):
3402 if not _validname(name):
3403 raise error.Abort(
3403 raise error.Abort(
3404 _('invalid queue name, may not contain the characters ":\\/."'))
3404 _('invalid queue name, may not contain the characters ":\\/."'))
3405
3405
3406 with repo.wlock():
3406 with repo.wlock():
3407 existing = _getqueues()
3407 existing = _getqueues()
3408
3408
3409 if opts.get('create'):
3409 if opts.get('create'):
3410 if name in existing:
3410 if name in existing:
3411 raise error.Abort(_('queue "%s" already exists') % name)
3411 raise error.Abort(_('queue "%s" already exists') % name)
3412 if _noqueues():
3412 if _noqueues():
3413 _addqueue(_defaultqueue)
3413 _addqueue(_defaultqueue)
3414 _addqueue(name)
3414 _addqueue(name)
3415 _setactive(name)
3415 _setactive(name)
3416 elif opts.get('rename'):
3416 elif opts.get('rename'):
3417 current = _getcurrent()
3417 current = _getcurrent()
3418 if name == current:
3418 if name == current:
3419 raise error.Abort(_('can\'t rename "%s" to its current name')
3419 raise error.Abort(_('can\'t rename "%s" to its current name')
3420 % name)
3420 % name)
3421 if name in existing:
3421 if name in existing:
3422 raise error.Abort(_('queue "%s" already exists') % name)
3422 raise error.Abort(_('queue "%s" already exists') % name)
3423
3423
3424 olddir = _queuedir(current)
3424 olddir = _queuedir(current)
3425 newdir = _queuedir(name)
3425 newdir = _queuedir(name)
3426
3426
3427 if os.path.exists(newdir):
3427 if os.path.exists(newdir):
3428 raise error.Abort(_('non-queue directory "%s" already exists') %
3428 raise error.Abort(_('non-queue directory "%s" already exists') %
3429 newdir)
3429 newdir)
3430
3430
3431 fh = repo.vfs('patches.queues.new', 'w')
3431 fh = repo.vfs('patches.queues.new', 'w')
3432 for queue in existing:
3432 for queue in existing:
3433 if queue == current:
3433 if queue == current:
3434 fh.write('%s\n' % (name,))
3434 fh.write('%s\n' % (name,))
3435 if os.path.exists(olddir):
3435 if os.path.exists(olddir):
3436 util.rename(olddir, newdir)
3436 util.rename(olddir, newdir)
3437 else:
3437 else:
3438 fh.write('%s\n' % (queue,))
3438 fh.write('%s\n' % (queue,))
3439 fh.close()
3439 fh.close()
3440 repo.vfs.rename('patches.queues.new', _allqueues)
3440 repo.vfs.rename('patches.queues.new', _allqueues)
3441 _setactivenocheck(name)
3441 _setactivenocheck(name)
3442 elif opts.get('delete'):
3442 elif opts.get('delete'):
3443 _delete(name)
3443 _delete(name)
3444 elif opts.get('purge'):
3444 elif opts.get('purge'):
3445 if name in existing:
3445 if name in existing:
3446 _delete(name)
3446 _delete(name)
3447 qdir = _queuedir(name)
3447 qdir = _queuedir(name)
3448 if os.path.exists(qdir):
3448 if os.path.exists(qdir):
3449 shutil.rmtree(qdir)
3449 shutil.rmtree(qdir)
3450 else:
3450 else:
3451 if name not in existing:
3451 if name not in existing:
3452 raise error.Abort(_('use --create to create a new queue'))
3452 raise error.Abort(_('use --create to create a new queue'))
3453 _setactive(name)
3453 _setactive(name)
3454
3454
3455 def mqphasedefaults(repo, roots):
3455 def mqphasedefaults(repo, roots):
3456 """callback used to set mq changeset as secret when no phase data exists"""
3456 """callback used to set mq changeset as secret when no phase data exists"""
3457 if repo.mq.applied:
3457 if repo.mq.applied:
3458 if repo.ui.configbool('mq', 'secret'):
3458 if repo.ui.configbool('mq', 'secret'):
3459 mqphase = phases.secret
3459 mqphase = phases.secret
3460 else:
3460 else:
3461 mqphase = phases.draft
3461 mqphase = phases.draft
3462 qbase = repo[repo.mq.applied[0].node]
3462 qbase = repo[repo.mq.applied[0].node]
3463 roots[mqphase].add(qbase.node())
3463 roots[mqphase].add(qbase.node())
3464 return roots
3464 return roots
3465
3465
3466 def reposetup(ui, repo):
3466 def reposetup(ui, repo):
3467 class mqrepo(repo.__class__):
3467 class mqrepo(repo.__class__):
3468 @localrepo.unfilteredpropertycache
3468 @localrepo.unfilteredpropertycache
3469 def mq(self):
3469 def mq(self):
3470 return queue(self.ui, self.baseui, self.path)
3470 return queue(self.ui, self.baseui, self.path)
3471
3471
3472 def invalidateall(self):
3472 def invalidateall(self):
3473 super(mqrepo, self).invalidateall()
3473 super(mqrepo, self).invalidateall()
3474 if localrepo.hasunfilteredcache(self, 'mq'):
3474 if localrepo.hasunfilteredcache(self, 'mq'):
3475 # recreate mq in case queue path was changed
3475 # recreate mq in case queue path was changed
3476 delattr(self.unfiltered(), 'mq')
3476 delattr(self.unfiltered(), 'mq')
3477
3477
3478 def abortifwdirpatched(self, errmsg, force=False):
3478 def abortifwdirpatched(self, errmsg, force=False):
3479 if self.mq.applied and self.mq.checkapplied and not force:
3479 if self.mq.applied and self.mq.checkapplied and not force:
3480 parents = self.dirstate.parents()
3480 parents = self.dirstate.parents()
3481 patches = [s.node for s in self.mq.applied]
3481 patches = [s.node for s in self.mq.applied]
3482 if parents[0] in patches or parents[1] in patches:
3482 if parents[0] in patches or parents[1] in patches:
3483 raise error.Abort(errmsg)
3483 raise error.Abort(errmsg)
3484
3484
3485 def commit(self, text="", user=None, date=None, match=None,
3485 def commit(self, text="", user=None, date=None, match=None,
3486 force=False, editor=False, extra=None):
3486 force=False, editor=False, extra=None):
3487 if extra is None:
3487 if extra is None:
3488 extra = {}
3488 extra = {}
3489 self.abortifwdirpatched(
3489 self.abortifwdirpatched(
3490 _('cannot commit over an applied mq patch'),
3490 _('cannot commit over an applied mq patch'),
3491 force)
3491 force)
3492
3492
3493 return super(mqrepo, self).commit(text, user, date, match, force,
3493 return super(mqrepo, self).commit(text, user, date, match, force,
3494 editor, extra)
3494 editor, extra)
3495
3495
3496 def checkpush(self, pushop):
3496 def checkpush(self, pushop):
3497 if self.mq.applied and self.mq.checkapplied and not pushop.force:
3497 if self.mq.applied and self.mq.checkapplied and not pushop.force:
3498 outapplied = [e.node for e in self.mq.applied]
3498 outapplied = [e.node for e in self.mq.applied]
3499 if pushop.revs:
3499 if pushop.revs:
3500 # Assume applied patches have no non-patch descendants and
3500 # Assume applied patches have no non-patch descendants and
3501 # are not on remote already. Filtering any changeset not
3501 # are not on remote already. Filtering any changeset not
3502 # pushed.
3502 # pushed.
3503 heads = set(pushop.revs)
3503 heads = set(pushop.revs)
3504 for node in reversed(outapplied):
3504 for node in reversed(outapplied):
3505 if node in heads:
3505 if node in heads:
3506 break
3506 break
3507 else:
3507 else:
3508 outapplied.pop()
3508 outapplied.pop()
3509 # looking for pushed and shared changeset
3509 # looking for pushed and shared changeset
3510 for node in outapplied:
3510 for node in outapplied:
3511 if self[node].phase() < phases.secret:
3511 if self[node].phase() < phases.secret:
3512 raise error.Abort(_('source has mq patches applied'))
3512 raise error.Abort(_('source has mq patches applied'))
3513 # no non-secret patches pushed
3513 # no non-secret patches pushed
3514 super(mqrepo, self).checkpush(pushop)
3514 super(mqrepo, self).checkpush(pushop)
3515
3515
3516 def _findtags(self):
3516 def _findtags(self):
3517 '''augment tags from base class with patch tags'''
3517 '''augment tags from base class with patch tags'''
3518 result = super(mqrepo, self)._findtags()
3518 result = super(mqrepo, self)._findtags()
3519
3519
3520 q = self.mq
3520 q = self.mq
3521 if not q.applied:
3521 if not q.applied:
3522 return result
3522 return result
3523
3523
3524 mqtags = [(patch.node, patch.name) for patch in q.applied]
3524 mqtags = [(patch.node, patch.name) for patch in q.applied]
3525
3525
3526 try:
3526 try:
3527 # for now ignore filtering business
3527 # for now ignore filtering business
3528 self.unfiltered().changelog.rev(mqtags[-1][0])
3528 self.unfiltered().changelog.rev(mqtags[-1][0])
3529 except error.LookupError:
3529 except error.LookupError:
3530 self.ui.warn(_('mq status file refers to unknown node %s\n')
3530 self.ui.warn(_('mq status file refers to unknown node %s\n')
3531 % short(mqtags[-1][0]))
3531 % short(mqtags[-1][0]))
3532 return result
3532 return result
3533
3533
3534 # do not add fake tags for filtered revisions
3534 # do not add fake tags for filtered revisions
3535 included = self.changelog.hasnode
3535 included = self.changelog.hasnode
3536 mqtags = [mqt for mqt in mqtags if included(mqt[0])]
3536 mqtags = [mqt for mqt in mqtags if included(mqt[0])]
3537 if not mqtags:
3537 if not mqtags:
3538 return result
3538 return result
3539
3539
3540 mqtags.append((mqtags[-1][0], 'qtip'))
3540 mqtags.append((mqtags[-1][0], 'qtip'))
3541 mqtags.append((mqtags[0][0], 'qbase'))
3541 mqtags.append((mqtags[0][0], 'qbase'))
3542 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
3542 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
3543 tags = result[0]
3543 tags = result[0]
3544 for patch in mqtags:
3544 for patch in mqtags:
3545 if patch[1] in tags:
3545 if patch[1] in tags:
3546 self.ui.warn(_('tag %s overrides mq patch of the same '
3546 self.ui.warn(_('tag %s overrides mq patch of the same '
3547 'name\n') % patch[1])
3547 'name\n') % patch[1])
3548 else:
3548 else:
3549 tags[patch[1]] = patch[0]
3549 tags[patch[1]] = patch[0]
3550
3550
3551 return result
3551 return result
3552
3552
3553 if repo.local():
3553 if repo.local():
3554 repo.__class__ = mqrepo
3554 repo.__class__ = mqrepo
3555
3555
3556 repo._phasedefaults.append(mqphasedefaults)
3556 repo._phasedefaults.append(mqphasedefaults)
3557
3557
3558 def mqimport(orig, ui, repo, *args, **kwargs):
3558 def mqimport(orig, ui, repo, *args, **kwargs):
3559 if (util.safehasattr(repo, 'abortifwdirpatched')
3559 if (util.safehasattr(repo, 'abortifwdirpatched')
3560 and not kwargs.get(r'no_commit', False)):
3560 and not kwargs.get(r'no_commit', False)):
3561 repo.abortifwdirpatched(_('cannot import over an applied patch'),
3561 repo.abortifwdirpatched(_('cannot import over an applied patch'),
3562 kwargs.get(r'force'))
3562 kwargs.get(r'force'))
3563 return orig(ui, repo, *args, **kwargs)
3563 return orig(ui, repo, *args, **kwargs)
3564
3564
3565 def mqinit(orig, ui, *args, **kwargs):
3565 def mqinit(orig, ui, *args, **kwargs):
3566 mq = kwargs.pop(r'mq', None)
3566 mq = kwargs.pop(r'mq', None)
3567
3567
3568 if not mq:
3568 if not mq:
3569 return orig(ui, *args, **kwargs)
3569 return orig(ui, *args, **kwargs)
3570
3570
3571 if args:
3571 if args:
3572 repopath = args[0]
3572 repopath = args[0]
3573 if not hg.islocal(repopath):
3573 if not hg.islocal(repopath):
3574 raise error.Abort(_('only a local queue repository '
3574 raise error.Abort(_('only a local queue repository '
3575 'may be initialized'))
3575 'may be initialized'))
3576 else:
3576 else:
3577 repopath = cmdutil.findrepo(pycompat.getcwd())
3577 repopath = cmdutil.findrepo(pycompat.getcwd())
3578 if not repopath:
3578 if not repopath:
3579 raise error.Abort(_('there is no Mercurial repository here '
3579 raise error.Abort(_('there is no Mercurial repository here '
3580 '(.hg not found)'))
3580 '(.hg not found)'))
3581 repo = hg.repository(ui, repopath)
3581 repo = hg.repository(ui, repopath)
3582 return qinit(ui, repo, True)
3582 return qinit(ui, repo, True)
3583
3583
3584 def mqcommand(orig, ui, repo, *args, **kwargs):
3584 def mqcommand(orig, ui, repo, *args, **kwargs):
3585 """Add --mq option to operate on patch repository instead of main"""
3585 """Add --mq option to operate on patch repository instead of main"""
3586
3586
3587 # some commands do not like getting unknown options
3587 # some commands do not like getting unknown options
3588 mq = kwargs.pop(r'mq', None)
3588 mq = kwargs.pop(r'mq', None)
3589
3589
3590 if not mq:
3590 if not mq:
3591 return orig(ui, repo, *args, **kwargs)
3591 return orig(ui, repo, *args, **kwargs)
3592
3592
3593 q = repo.mq
3593 q = repo.mq
3594 r = q.qrepo()
3594 r = q.qrepo()
3595 if not r:
3595 if not r:
3596 raise error.Abort(_('no queue repository'))
3596 raise error.Abort(_('no queue repository'))
3597 return orig(r.ui, r, *args, **kwargs)
3597 return orig(r.ui, r, *args, **kwargs)
3598
3598
3599 def summaryhook(ui, repo):
3599 def summaryhook(ui, repo):
3600 q = repo.mq
3600 q = repo.mq
3601 m = []
3601 m = []
3602 a, u = len(q.applied), len(q.unapplied(repo))
3602 a, u = len(q.applied), len(q.unapplied(repo))
3603 if a:
3603 if a:
3604 m.append(ui.label(_("%d applied"), 'qseries.applied') % a)
3604 m.append(ui.label(_("%d applied"), 'qseries.applied') % a)
3605 if u:
3605 if u:
3606 m.append(ui.label(_("%d unapplied"), 'qseries.unapplied') % u)
3606 m.append(ui.label(_("%d unapplied"), 'qseries.unapplied') % u)
3607 if m:
3607 if m:
3608 # i18n: column positioning for "hg summary"
3608 # i18n: column positioning for "hg summary"
3609 ui.write(_("mq: %s\n") % ', '.join(m))
3609 ui.write(_("mq: %s\n") % ', '.join(m))
3610 else:
3610 else:
3611 # i18n: column positioning for "hg summary"
3611 # i18n: column positioning for "hg summary"
3612 ui.note(_("mq: (empty queue)\n"))
3612 ui.note(_("mq: (empty queue)\n"))
3613
3613
3614 revsetpredicate = registrar.revsetpredicate()
3614 revsetpredicate = registrar.revsetpredicate()
3615
3615
3616 @revsetpredicate('mq()')
3616 @revsetpredicate('mq()')
3617 def revsetmq(repo, subset, x):
3617 def revsetmq(repo, subset, x):
3618 """Changesets managed by MQ.
3618 """Changesets managed by MQ.
3619 """
3619 """
3620 revsetlang.getargs(x, 0, 0, _("mq takes no arguments"))
3620 revsetlang.getargs(x, 0, 0, _("mq takes no arguments"))
3621 applied = set([repo[r.node].rev() for r in repo.mq.applied])
3621 applied = set([repo[r.node].rev() for r in repo.mq.applied])
3622 return smartset.baseset([r for r in subset if r in applied])
3622 return smartset.baseset([r for r in subset if r in applied])
3623
3623
3624 # tell hggettext to extract docstrings from these functions:
3624 # tell hggettext to extract docstrings from these functions:
3625 i18nfunctions = [revsetmq]
3625 i18nfunctions = [revsetmq]
3626
3626
3627 def extsetup(ui):
3627 def extsetup(ui):
3628 # Ensure mq wrappers are called first, regardless of extension load order by
3628 # Ensure mq wrappers are called first, regardless of extension load order by
3629 # NOT wrapping in uisetup() and instead deferring to init stage two here.
3629 # NOT wrapping in uisetup() and instead deferring to init stage two here.
3630 mqopt = [('', 'mq', None, _("operate on patch repository"))]
3630 mqopt = [('', 'mq', None, _("operate on patch repository"))]
3631
3631
3632 extensions.wrapcommand(commands.table, 'import', mqimport)
3632 extensions.wrapcommand(commands.table, 'import', mqimport)
3633 cmdutil.summaryhooks.add('mq', summaryhook)
3633 cmdutil.summaryhooks.add('mq', summaryhook)
3634
3634
3635 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
3635 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
3636 entry[1].extend(mqopt)
3636 entry[1].extend(mqopt)
3637
3637
3638 def dotable(cmdtable):
3638 def dotable(cmdtable):
3639 for cmd, entry in cmdtable.iteritems():
3639 for cmd, entry in cmdtable.iteritems():
3640 cmd = cmdutil.parsealiases(cmd)[0]
3640 cmd = cmdutil.parsealiases(cmd)[0]
3641 func = entry[0]
3641 func = entry[0]
3642 if func.norepo:
3642 if func.norepo:
3643 continue
3643 continue
3644 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
3644 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
3645 entry[1].extend(mqopt)
3645 entry[1].extend(mqopt)
3646
3646
3647 dotable(commands.table)
3647 dotable(commands.table)
3648
3648
3649 for extname, extmodule in extensions.extensions():
3649 for extname, extmodule in extensions.extensions():
3650 if extmodule.__file__ != __file__:
3650 if extmodule.__file__ != __file__:
3651 dotable(getattr(extmodule, 'cmdtable', {}))
3651 dotable(getattr(extmodule, 'cmdtable', {}))
3652
3652
3653 colortable = {'qguard.negative': 'red',
3653 colortable = {'qguard.negative': 'red',
3654 'qguard.positive': 'yellow',
3654 'qguard.positive': 'yellow',
3655 'qguard.unguarded': 'green',
3655 'qguard.unguarded': 'green',
3656 'qseries.applied': 'blue bold underline',
3656 'qseries.applied': 'blue bold underline',
3657 'qseries.guarded': 'black bold',
3657 'qseries.guarded': 'black bold',
3658 'qseries.missing': 'red bold',
3658 'qseries.missing': 'red bold',
3659 'qseries.unapplied': 'black bold'}
3659 'qseries.unapplied': 'black bold'}
@@ -1,5640 +1,5640 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 import sys
14 import sys
15
15
16 from .i18n import _
16 from .i18n import _
17 from .node import (
17 from .node import (
18 hex,
18 hex,
19 nullid,
19 nullid,
20 nullrev,
20 nullrev,
21 short,
21 short,
22 )
22 )
23 from . import (
23 from . import (
24 archival,
24 archival,
25 bookmarks,
25 bookmarks,
26 bundle2,
26 bundle2,
27 changegroup,
27 changegroup,
28 cmdutil,
28 cmdutil,
29 copies,
29 copies,
30 debugcommands as debugcommandsmod,
30 debugcommands as debugcommandsmod,
31 destutil,
31 destutil,
32 dirstateguard,
32 dirstateguard,
33 discovery,
33 discovery,
34 encoding,
34 encoding,
35 error,
35 error,
36 exchange,
36 exchange,
37 extensions,
37 extensions,
38 formatter,
38 formatter,
39 graphmod,
39 graphmod,
40 hbisect,
40 hbisect,
41 help,
41 help,
42 hg,
42 hg,
43 lock as lockmod,
43 lock as lockmod,
44 logcmdutil,
44 logcmdutil,
45 merge as mergemod,
45 merge as mergemod,
46 obsolete,
46 obsolete,
47 obsutil,
47 obsutil,
48 patch,
48 patch,
49 phases,
49 phases,
50 pycompat,
50 pycompat,
51 rcutil,
51 rcutil,
52 registrar,
52 registrar,
53 revsetlang,
53 revsetlang,
54 rewriteutil,
54 rewriteutil,
55 scmutil,
55 scmutil,
56 server,
56 server,
57 streamclone,
57 streamclone,
58 tags as tagsmod,
58 tags as tagsmod,
59 templatekw,
59 templatekw,
60 ui as uimod,
60 ui as uimod,
61 util,
61 util,
62 wireprotoserver,
62 wireprotoserver,
63 )
63 )
64 from .utils import (
64 from .utils import (
65 dateutil,
65 dateutil,
66 procutil,
66 procutil,
67 stringutil,
67 stringutil,
68 )
68 )
69
69
70 release = lockmod.release
70 release = lockmod.release
71
71
72 table = {}
72 table = {}
73 table.update(debugcommandsmod.command._table)
73 table.update(debugcommandsmod.command._table)
74
74
75 command = registrar.command(table)
75 command = registrar.command(table)
76 readonly = registrar.command.readonly
76 readonly = registrar.command.readonly
77
77
78 # common command options
78 # common command options
79
79
80 globalopts = [
80 globalopts = [
81 ('R', 'repository', '',
81 ('R', 'repository', '',
82 _('repository root directory or name of overlay bundle file'),
82 _('repository root directory or name of overlay bundle file'),
83 _('REPO')),
83 _('REPO')),
84 ('', 'cwd', '',
84 ('', 'cwd', '',
85 _('change working directory'), _('DIR')),
85 _('change working directory'), _('DIR')),
86 ('y', 'noninteractive', None,
86 ('y', 'noninteractive', None,
87 _('do not prompt, automatically pick the first choice for all prompts')),
87 _('do not prompt, automatically pick the first choice for all prompts')),
88 ('q', 'quiet', None, _('suppress output')),
88 ('q', 'quiet', None, _('suppress output')),
89 ('v', 'verbose', None, _('enable additional output')),
89 ('v', 'verbose', None, _('enable additional output')),
90 ('', 'color', '',
90 ('', 'color', '',
91 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
91 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
92 # and should not be translated
92 # and should not be translated
93 _("when to colorize (boolean, always, auto, never, or debug)"),
93 _("when to colorize (boolean, always, auto, never, or debug)"),
94 _('TYPE')),
94 _('TYPE')),
95 ('', 'config', [],
95 ('', 'config', [],
96 _('set/override config option (use \'section.name=value\')'),
96 _('set/override config option (use \'section.name=value\')'),
97 _('CONFIG')),
97 _('CONFIG')),
98 ('', 'debug', None, _('enable debugging output')),
98 ('', 'debug', None, _('enable debugging output')),
99 ('', 'debugger', None, _('start debugger')),
99 ('', 'debugger', None, _('start debugger')),
100 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
100 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
101 _('ENCODE')),
101 _('ENCODE')),
102 ('', 'encodingmode', encoding.encodingmode,
102 ('', 'encodingmode', encoding.encodingmode,
103 _('set the charset encoding mode'), _('MODE')),
103 _('set the charset encoding mode'), _('MODE')),
104 ('', 'traceback', None, _('always print a traceback on exception')),
104 ('', 'traceback', None, _('always print a traceback on exception')),
105 ('', 'time', None, _('time how long the command takes')),
105 ('', 'time', None, _('time how long the command takes')),
106 ('', 'profile', None, _('print command execution profile')),
106 ('', 'profile', None, _('print command execution profile')),
107 ('', 'version', None, _('output version information and exit')),
107 ('', 'version', None, _('output version information and exit')),
108 ('h', 'help', None, _('display help and exit')),
108 ('h', 'help', None, _('display help and exit')),
109 ('', 'hidden', False, _('consider hidden changesets')),
109 ('', 'hidden', False, _('consider hidden changesets')),
110 ('', 'pager', 'auto',
110 ('', 'pager', 'auto',
111 _("when to paginate (boolean, always, auto, or never)"), _('TYPE')),
111 _("when to paginate (boolean, always, auto, or never)"), _('TYPE')),
112 ]
112 ]
113
113
114 dryrunopts = cmdutil.dryrunopts
114 dryrunopts = cmdutil.dryrunopts
115 remoteopts = cmdutil.remoteopts
115 remoteopts = cmdutil.remoteopts
116 walkopts = cmdutil.walkopts
116 walkopts = cmdutil.walkopts
117 commitopts = cmdutil.commitopts
117 commitopts = cmdutil.commitopts
118 commitopts2 = cmdutil.commitopts2
118 commitopts2 = cmdutil.commitopts2
119 formatteropts = cmdutil.formatteropts
119 formatteropts = cmdutil.formatteropts
120 templateopts = cmdutil.templateopts
120 templateopts = cmdutil.templateopts
121 logopts = cmdutil.logopts
121 logopts = cmdutil.logopts
122 diffopts = cmdutil.diffopts
122 diffopts = cmdutil.diffopts
123 diffwsopts = cmdutil.diffwsopts
123 diffwsopts = cmdutil.diffwsopts
124 diffopts2 = cmdutil.diffopts2
124 diffopts2 = cmdutil.diffopts2
125 mergetoolopts = cmdutil.mergetoolopts
125 mergetoolopts = cmdutil.mergetoolopts
126 similarityopts = cmdutil.similarityopts
126 similarityopts = cmdutil.similarityopts
127 subrepoopts = cmdutil.subrepoopts
127 subrepoopts = cmdutil.subrepoopts
128 debugrevlogopts = cmdutil.debugrevlogopts
128 debugrevlogopts = cmdutil.debugrevlogopts
129
129
130 # Commands start here, listed alphabetically
130 # Commands start here, listed alphabetically
131
131
132 @command('^add',
132 @command('^add',
133 walkopts + subrepoopts + dryrunopts,
133 walkopts + subrepoopts + dryrunopts,
134 _('[OPTION]... [FILE]...'),
134 _('[OPTION]... [FILE]...'),
135 inferrepo=True)
135 inferrepo=True)
136 def add(ui, repo, *pats, **opts):
136 def add(ui, repo, *pats, **opts):
137 """add the specified files on the next commit
137 """add the specified files on the next commit
138
138
139 Schedule files to be version controlled and added to the
139 Schedule files to be version controlled and added to the
140 repository.
140 repository.
141
141
142 The files will be added to the repository at the next commit. To
142 The files will be added to the repository at the next commit. To
143 undo an add before that, see :hg:`forget`.
143 undo an add before that, see :hg:`forget`.
144
144
145 If no names are given, add all files to the repository (except
145 If no names are given, add all files to the repository (except
146 files matching ``.hgignore``).
146 files matching ``.hgignore``).
147
147
148 .. container:: verbose
148 .. container:: verbose
149
149
150 Examples:
150 Examples:
151
151
152 - New (unknown) files are added
152 - New (unknown) files are added
153 automatically by :hg:`add`::
153 automatically by :hg:`add`::
154
154
155 $ ls
155 $ ls
156 foo.c
156 foo.c
157 $ hg status
157 $ hg status
158 ? foo.c
158 ? foo.c
159 $ hg add
159 $ hg add
160 adding foo.c
160 adding foo.c
161 $ hg status
161 $ hg status
162 A foo.c
162 A foo.c
163
163
164 - Specific files to be added can be specified::
164 - Specific files to be added can be specified::
165
165
166 $ ls
166 $ ls
167 bar.c foo.c
167 bar.c foo.c
168 $ hg status
168 $ hg status
169 ? bar.c
169 ? bar.c
170 ? foo.c
170 ? foo.c
171 $ hg add bar.c
171 $ hg add bar.c
172 $ hg status
172 $ hg status
173 A bar.c
173 A bar.c
174 ? foo.c
174 ? foo.c
175
175
176 Returns 0 if all files are successfully added.
176 Returns 0 if all files are successfully added.
177 """
177 """
178
178
179 m = scmutil.match(repo[None], pats, pycompat.byteskwargs(opts))
179 m = scmutil.match(repo[None], pats, pycompat.byteskwargs(opts))
180 rejected = cmdutil.add(ui, repo, m, "", False, **opts)
180 rejected = cmdutil.add(ui, repo, m, "", False, **opts)
181 return rejected and 1 or 0
181 return rejected and 1 or 0
182
182
183 @command('addremove',
183 @command('addremove',
184 similarityopts + subrepoopts + walkopts + dryrunopts,
184 similarityopts + subrepoopts + walkopts + dryrunopts,
185 _('[OPTION]... [FILE]...'),
185 _('[OPTION]... [FILE]...'),
186 inferrepo=True)
186 inferrepo=True)
187 def addremove(ui, repo, *pats, **opts):
187 def addremove(ui, repo, *pats, **opts):
188 """add all new files, delete all missing files
188 """add all new files, delete all missing files
189
189
190 Add all new files and remove all missing files from the
190 Add all new files and remove all missing files from the
191 repository.
191 repository.
192
192
193 Unless names are given, new files are ignored if they match any of
193 Unless names are given, new files are ignored if they match any of
194 the patterns in ``.hgignore``. As with add, these changes take
194 the patterns in ``.hgignore``. As with add, these changes take
195 effect at the next commit.
195 effect at the next commit.
196
196
197 Use the -s/--similarity option to detect renamed files. This
197 Use the -s/--similarity option to detect renamed files. This
198 option takes a percentage between 0 (disabled) and 100 (files must
198 option takes a percentage between 0 (disabled) and 100 (files must
199 be identical) as its parameter. With a parameter greater than 0,
199 be identical) as its parameter. With a parameter greater than 0,
200 this compares every removed file with every added file and records
200 this compares every removed file with every added file and records
201 those similar enough as renames. Detecting renamed files this way
201 those similar enough as renames. Detecting renamed files this way
202 can be expensive. After using this option, :hg:`status -C` can be
202 can be expensive. After using this option, :hg:`status -C` can be
203 used to check which files were identified as moved or renamed. If
203 used to check which files were identified as moved or renamed. If
204 not specified, -s/--similarity defaults to 100 and only renames of
204 not specified, -s/--similarity defaults to 100 and only renames of
205 identical files are detected.
205 identical files are detected.
206
206
207 .. container:: verbose
207 .. container:: verbose
208
208
209 Examples:
209 Examples:
210
210
211 - A number of files (bar.c and foo.c) are new,
211 - A number of files (bar.c and foo.c) are new,
212 while foobar.c has been removed (without using :hg:`remove`)
212 while foobar.c has been removed (without using :hg:`remove`)
213 from the repository::
213 from the repository::
214
214
215 $ ls
215 $ ls
216 bar.c foo.c
216 bar.c foo.c
217 $ hg status
217 $ hg status
218 ! foobar.c
218 ! foobar.c
219 ? bar.c
219 ? bar.c
220 ? foo.c
220 ? foo.c
221 $ hg addremove
221 $ hg addremove
222 adding bar.c
222 adding bar.c
223 adding foo.c
223 adding foo.c
224 removing foobar.c
224 removing foobar.c
225 $ hg status
225 $ hg status
226 A bar.c
226 A bar.c
227 A foo.c
227 A foo.c
228 R foobar.c
228 R foobar.c
229
229
230 - A file foobar.c was moved to foo.c without using :hg:`rename`.
230 - A file foobar.c was moved to foo.c without using :hg:`rename`.
231 Afterwards, it was edited slightly::
231 Afterwards, it was edited slightly::
232
232
233 $ ls
233 $ ls
234 foo.c
234 foo.c
235 $ hg status
235 $ hg status
236 ! foobar.c
236 ! foobar.c
237 ? foo.c
237 ? foo.c
238 $ hg addremove --similarity 90
238 $ hg addremove --similarity 90
239 removing foobar.c
239 removing foobar.c
240 adding foo.c
240 adding foo.c
241 recording removal of foobar.c as rename to foo.c (94% similar)
241 recording removal of foobar.c as rename to foo.c (94% similar)
242 $ hg status -C
242 $ hg status -C
243 A foo.c
243 A foo.c
244 foobar.c
244 foobar.c
245 R foobar.c
245 R foobar.c
246
246
247 Returns 0 if all files are successfully added.
247 Returns 0 if all files are successfully added.
248 """
248 """
249 opts = pycompat.byteskwargs(opts)
249 opts = pycompat.byteskwargs(opts)
250 try:
250 try:
251 sim = float(opts.get('similarity') or 100)
251 sim = float(opts.get('similarity') or 100)
252 except ValueError:
252 except ValueError:
253 raise error.Abort(_('similarity must be a number'))
253 raise error.Abort(_('similarity must be a number'))
254 if sim < 0 or sim > 100:
254 if sim < 0 or sim > 100:
255 raise error.Abort(_('similarity must be between 0 and 100'))
255 raise error.Abort(_('similarity must be between 0 and 100'))
256 matcher = scmutil.match(repo[None], pats, opts)
256 matcher = scmutil.match(repo[None], pats, opts)
257 return scmutil.addremove(repo, matcher, "", opts, similarity=sim / 100.0)
257 return scmutil.addremove(repo, matcher, "", opts, similarity=sim / 100.0)
258
258
259 @command('^annotate|blame',
259 @command('^annotate|blame',
260 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
260 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
261 ('', 'follow', None,
261 ('', 'follow', None,
262 _('follow copies/renames and list the filename (DEPRECATED)')),
262 _('follow copies/renames and list the filename (DEPRECATED)')),
263 ('', 'no-follow', None, _("don't follow copies and renames")),
263 ('', 'no-follow', None, _("don't follow copies and renames")),
264 ('a', 'text', None, _('treat all files as text')),
264 ('a', 'text', None, _('treat all files as text')),
265 ('u', 'user', None, _('list the author (long with -v)')),
265 ('u', 'user', None, _('list the author (long with -v)')),
266 ('f', 'file', None, _('list the filename')),
266 ('f', 'file', None, _('list the filename')),
267 ('d', 'date', None, _('list the date (short with -q)')),
267 ('d', 'date', None, _('list the date (short with -q)')),
268 ('n', 'number', None, _('list the revision number (default)')),
268 ('n', 'number', None, _('list the revision number (default)')),
269 ('c', 'changeset', None, _('list the changeset')),
269 ('c', 'changeset', None, _('list the changeset')),
270 ('l', 'line-number', None, _('show line number at the first appearance')),
270 ('l', 'line-number', None, _('show line number at the first appearance')),
271 ('', 'skip', [], _('revision to not display (EXPERIMENTAL)'), _('REV')),
271 ('', 'skip', [], _('revision to not display (EXPERIMENTAL)'), _('REV')),
272 ] + diffwsopts + walkopts + formatteropts,
272 ] + diffwsopts + walkopts + formatteropts,
273 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
273 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
274 inferrepo=True)
274 inferrepo=True)
275 def annotate(ui, repo, *pats, **opts):
275 def annotate(ui, repo, *pats, **opts):
276 """show changeset information by line for each file
276 """show changeset information by line for each file
277
277
278 List changes in files, showing the revision id responsible for
278 List changes in files, showing the revision id responsible for
279 each line.
279 each line.
280
280
281 This command is useful for discovering when a change was made and
281 This command is useful for discovering when a change was made and
282 by whom.
282 by whom.
283
283
284 If you include --file, --user, or --date, the revision number is
284 If you include --file, --user, or --date, the revision number is
285 suppressed unless you also include --number.
285 suppressed unless you also include --number.
286
286
287 Without the -a/--text option, annotate will avoid processing files
287 Without the -a/--text option, annotate will avoid processing files
288 it detects as binary. With -a, annotate will annotate the file
288 it detects as binary. With -a, annotate will annotate the file
289 anyway, although the results will probably be neither useful
289 anyway, although the results will probably be neither useful
290 nor desirable.
290 nor desirable.
291
291
292 Returns 0 on success.
292 Returns 0 on success.
293 """
293 """
294 opts = pycompat.byteskwargs(opts)
294 opts = pycompat.byteskwargs(opts)
295 if not pats:
295 if not pats:
296 raise error.Abort(_('at least one filename or pattern is required'))
296 raise error.Abort(_('at least one filename or pattern is required'))
297
297
298 if opts.get('follow'):
298 if opts.get('follow'):
299 # --follow is deprecated and now just an alias for -f/--file
299 # --follow is deprecated and now just an alias for -f/--file
300 # to mimic the behavior of Mercurial before version 1.5
300 # to mimic the behavior of Mercurial before version 1.5
301 opts['file'] = True
301 opts['file'] = True
302
302
303 rev = opts.get('rev')
303 rev = opts.get('rev')
304 if rev:
304 if rev:
305 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
305 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
306 ctx = scmutil.revsingle(repo, rev)
306 ctx = scmutil.revsingle(repo, rev)
307
307
308 rootfm = ui.formatter('annotate', opts)
308 rootfm = ui.formatter('annotate', opts)
309 if ui.quiet:
309 if ui.quiet:
310 datefunc = dateutil.shortdate
310 datefunc = dateutil.shortdate
311 else:
311 else:
312 datefunc = dateutil.datestr
312 datefunc = dateutil.datestr
313 if ctx.rev() is None:
313 if ctx.rev() is None:
314 def hexfn(node):
314 def hexfn(node):
315 if node is None:
315 if node is None:
316 return None
316 return None
317 else:
317 else:
318 return rootfm.hexfunc(node)
318 return rootfm.hexfunc(node)
319 if opts.get('changeset'):
319 if opts.get('changeset'):
320 # omit "+" suffix which is appended to node hex
320 # omit "+" suffix which is appended to node hex
321 def formatrev(rev):
321 def formatrev(rev):
322 if rev is None:
322 if rev is None:
323 return '%d' % ctx.p1().rev()
323 return '%d' % ctx.p1().rev()
324 else:
324 else:
325 return '%d' % rev
325 return '%d' % rev
326 else:
326 else:
327 def formatrev(rev):
327 def formatrev(rev):
328 if rev is None:
328 if rev is None:
329 return '%d+' % ctx.p1().rev()
329 return '%d+' % ctx.p1().rev()
330 else:
330 else:
331 return '%d ' % rev
331 return '%d ' % rev
332 def formathex(hex):
332 def formathex(hex):
333 if hex is None:
333 if hex is None:
334 return '%s+' % rootfm.hexfunc(ctx.p1().node())
334 return '%s+' % rootfm.hexfunc(ctx.p1().node())
335 else:
335 else:
336 return '%s ' % hex
336 return '%s ' % hex
337 else:
337 else:
338 hexfn = rootfm.hexfunc
338 hexfn = rootfm.hexfunc
339 formatrev = formathex = pycompat.bytestr
339 formatrev = formathex = pycompat.bytestr
340
340
341 opmap = [('user', ' ', lambda x: x.fctx.user(), ui.shortuser),
341 opmap = [('user', ' ', lambda x: x.fctx.user(), ui.shortuser),
342 ('number', ' ', lambda x: x.fctx.rev(), formatrev),
342 ('number', ' ', lambda x: x.fctx.rev(), formatrev),
343 ('changeset', ' ', lambda x: hexfn(x.fctx.node()), formathex),
343 ('changeset', ' ', lambda x: hexfn(x.fctx.node()), formathex),
344 ('date', ' ', lambda x: x.fctx.date(), util.cachefunc(datefunc)),
344 ('date', ' ', lambda x: x.fctx.date(), util.cachefunc(datefunc)),
345 ('file', ' ', lambda x: x.fctx.path(), pycompat.bytestr),
345 ('file', ' ', lambda x: x.fctx.path(), pycompat.bytestr),
346 ('line_number', ':', lambda x: x.lineno, pycompat.bytestr),
346 ('line_number', ':', lambda x: x.lineno, pycompat.bytestr),
347 ]
347 ]
348 fieldnamemap = {'number': 'rev', 'changeset': 'node'}
348 fieldnamemap = {'number': 'rev', 'changeset': 'node'}
349
349
350 if (not opts.get('user') and not opts.get('changeset')
350 if (not opts.get('user') and not opts.get('changeset')
351 and not opts.get('date') and not opts.get('file')):
351 and not opts.get('date') and not opts.get('file')):
352 opts['number'] = True
352 opts['number'] = True
353
353
354 linenumber = opts.get('line_number') is not None
354 linenumber = opts.get('line_number') is not None
355 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
355 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
356 raise error.Abort(_('at least one of -n/-c is required for -l'))
356 raise error.Abort(_('at least one of -n/-c is required for -l'))
357
357
358 ui.pager('annotate')
358 ui.pager('annotate')
359
359
360 if rootfm.isplain():
360 if rootfm.isplain():
361 def makefunc(get, fmt):
361 def makefunc(get, fmt):
362 return lambda x: fmt(get(x))
362 return lambda x: fmt(get(x))
363 else:
363 else:
364 def makefunc(get, fmt):
364 def makefunc(get, fmt):
365 return get
365 return get
366 funcmap = [(makefunc(get, fmt), sep) for op, sep, get, fmt in opmap
366 funcmap = [(makefunc(get, fmt), sep) for op, sep, get, fmt in opmap
367 if opts.get(op)]
367 if opts.get(op)]
368 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
368 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
369 fields = ' '.join(fieldnamemap.get(op, op) for op, sep, get, fmt in opmap
369 fields = ' '.join(fieldnamemap.get(op, op) for op, sep, get, fmt in opmap
370 if opts.get(op))
370 if opts.get(op))
371
371
372 def bad(x, y):
372 def bad(x, y):
373 raise error.Abort("%s: %s" % (x, y))
373 raise error.Abort("%s: %s" % (x, y))
374
374
375 m = scmutil.match(ctx, pats, opts, badfn=bad)
375 m = scmutil.match(ctx, pats, opts, badfn=bad)
376
376
377 follow = not opts.get('no_follow')
377 follow = not opts.get('no_follow')
378 diffopts = patch.difffeatureopts(ui, opts, section='annotate',
378 diffopts = patch.difffeatureopts(ui, opts, section='annotate',
379 whitespace=True)
379 whitespace=True)
380 skiprevs = opts.get('skip')
380 skiprevs = opts.get('skip')
381 if skiprevs:
381 if skiprevs:
382 skiprevs = scmutil.revrange(repo, skiprevs)
382 skiprevs = scmutil.revrange(repo, skiprevs)
383
383
384 for abs in ctx.walk(m):
384 for abs in ctx.walk(m):
385 fctx = ctx[abs]
385 fctx = ctx[abs]
386 rootfm.startitem()
386 rootfm.startitem()
387 rootfm.data(abspath=abs, path=m.rel(abs))
387 rootfm.data(abspath=abs, path=m.rel(abs))
388 if not opts.get('text') and fctx.isbinary():
388 if not opts.get('text') and fctx.isbinary():
389 rootfm.plain(_("%s: binary file\n")
389 rootfm.plain(_("%s: binary file\n")
390 % ((pats and m.rel(abs)) or abs))
390 % ((pats and m.rel(abs)) or abs))
391 continue
391 continue
392
392
393 fm = rootfm.nested('lines')
393 fm = rootfm.nested('lines')
394 lines = fctx.annotate(follow=follow, skiprevs=skiprevs,
394 lines = fctx.annotate(follow=follow, skiprevs=skiprevs,
395 diffopts=diffopts)
395 diffopts=diffopts)
396 if not lines:
396 if not lines:
397 fm.end()
397 fm.end()
398 continue
398 continue
399 formats = []
399 formats = []
400 pieces = []
400 pieces = []
401
401
402 for f, sep in funcmap:
402 for f, sep in funcmap:
403 l = [f(n) for n in lines]
403 l = [f(n) for n in lines]
404 if fm.isplain():
404 if fm.isplain():
405 sizes = [encoding.colwidth(x) for x in l]
405 sizes = [encoding.colwidth(x) for x in l]
406 ml = max(sizes)
406 ml = max(sizes)
407 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
407 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
408 else:
408 else:
409 formats.append(['%s' for x in l])
409 formats.append(['%s' for x in l])
410 pieces.append(l)
410 pieces.append(l)
411
411
412 for f, p, n in zip(zip(*formats), zip(*pieces), lines):
412 for f, p, n in zip(zip(*formats), zip(*pieces), lines):
413 fm.startitem()
413 fm.startitem()
414 fm.context(fctx=n.fctx)
414 fm.context(fctx=n.fctx)
415 fm.write(fields, "".join(f), *p)
415 fm.write(fields, "".join(f), *p)
416 if n.skip:
416 if n.skip:
417 fmt = "* %s"
417 fmt = "* %s"
418 else:
418 else:
419 fmt = ": %s"
419 fmt = ": %s"
420 fm.write('line', fmt, n.text)
420 fm.write('line', fmt, n.text)
421
421
422 if not lines[-1].text.endswith('\n'):
422 if not lines[-1].text.endswith('\n'):
423 fm.plain('\n')
423 fm.plain('\n')
424 fm.end()
424 fm.end()
425
425
426 rootfm.end()
426 rootfm.end()
427
427
428 @command('archive',
428 @command('archive',
429 [('', 'no-decode', None, _('do not pass files through decoders')),
429 [('', 'no-decode', None, _('do not pass files through decoders')),
430 ('p', 'prefix', '', _('directory prefix for files in archive'),
430 ('p', 'prefix', '', _('directory prefix for files in archive'),
431 _('PREFIX')),
431 _('PREFIX')),
432 ('r', 'rev', '', _('revision to distribute'), _('REV')),
432 ('r', 'rev', '', _('revision to distribute'), _('REV')),
433 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
433 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
434 ] + subrepoopts + walkopts,
434 ] + subrepoopts + walkopts,
435 _('[OPTION]... DEST'))
435 _('[OPTION]... DEST'))
436 def archive(ui, repo, dest, **opts):
436 def archive(ui, repo, dest, **opts):
437 '''create an unversioned archive of a repository revision
437 '''create an unversioned archive of a repository revision
438
438
439 By default, the revision used is the parent of the working
439 By default, the revision used is the parent of the working
440 directory; use -r/--rev to specify a different revision.
440 directory; use -r/--rev to specify a different revision.
441
441
442 The archive type is automatically detected based on file
442 The archive type is automatically detected based on file
443 extension (to override, use -t/--type).
443 extension (to override, use -t/--type).
444
444
445 .. container:: verbose
445 .. container:: verbose
446
446
447 Examples:
447 Examples:
448
448
449 - create a zip file containing the 1.0 release::
449 - create a zip file containing the 1.0 release::
450
450
451 hg archive -r 1.0 project-1.0.zip
451 hg archive -r 1.0 project-1.0.zip
452
452
453 - create a tarball excluding .hg files::
453 - create a tarball excluding .hg files::
454
454
455 hg archive project.tar.gz -X ".hg*"
455 hg archive project.tar.gz -X ".hg*"
456
456
457 Valid types are:
457 Valid types are:
458
458
459 :``files``: a directory full of files (default)
459 :``files``: a directory full of files (default)
460 :``tar``: tar archive, uncompressed
460 :``tar``: tar archive, uncompressed
461 :``tbz2``: tar archive, compressed using bzip2
461 :``tbz2``: tar archive, compressed using bzip2
462 :``tgz``: tar archive, compressed using gzip
462 :``tgz``: tar archive, compressed using gzip
463 :``uzip``: zip archive, uncompressed
463 :``uzip``: zip archive, uncompressed
464 :``zip``: zip archive, compressed using deflate
464 :``zip``: zip archive, compressed using deflate
465
465
466 The exact name of the destination archive or directory is given
466 The exact name of the destination archive or directory is given
467 using a format string; see :hg:`help export` for details.
467 using a format string; see :hg:`help export` for details.
468
468
469 Each member added to an archive file has a directory prefix
469 Each member added to an archive file has a directory prefix
470 prepended. Use -p/--prefix to specify a format string for the
470 prepended. Use -p/--prefix to specify a format string for the
471 prefix. The default is the basename of the archive, with suffixes
471 prefix. The default is the basename of the archive, with suffixes
472 removed.
472 removed.
473
473
474 Returns 0 on success.
474 Returns 0 on success.
475 '''
475 '''
476
476
477 opts = pycompat.byteskwargs(opts)
477 opts = pycompat.byteskwargs(opts)
478 rev = opts.get('rev')
478 rev = opts.get('rev')
479 if rev:
479 if rev:
480 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
480 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
481 ctx = scmutil.revsingle(repo, rev)
481 ctx = scmutil.revsingle(repo, rev)
482 if not ctx:
482 if not ctx:
483 raise error.Abort(_('no working directory: please specify a revision'))
483 raise error.Abort(_('no working directory: please specify a revision'))
484 node = ctx.node()
484 node = ctx.node()
485 dest = cmdutil.makefilename(ctx, dest)
485 dest = cmdutil.makefilename(ctx, dest)
486 if os.path.realpath(dest) == repo.root:
486 if os.path.realpath(dest) == repo.root:
487 raise error.Abort(_('repository root cannot be destination'))
487 raise error.Abort(_('repository root cannot be destination'))
488
488
489 kind = opts.get('type') or archival.guesskind(dest) or 'files'
489 kind = opts.get('type') or archival.guesskind(dest) or 'files'
490 prefix = opts.get('prefix')
490 prefix = opts.get('prefix')
491
491
492 if dest == '-':
492 if dest == '-':
493 if kind == 'files':
493 if kind == 'files':
494 raise error.Abort(_('cannot archive plain files to stdout'))
494 raise error.Abort(_('cannot archive plain files to stdout'))
495 dest = cmdutil.makefileobj(ctx, dest)
495 dest = cmdutil.makefileobj(ctx, dest)
496 if not prefix:
496 if not prefix:
497 prefix = os.path.basename(repo.root) + '-%h'
497 prefix = os.path.basename(repo.root) + '-%h'
498
498
499 prefix = cmdutil.makefilename(ctx, prefix)
499 prefix = cmdutil.makefilename(ctx, prefix)
500 match = scmutil.match(ctx, [], opts)
500 match = scmutil.match(ctx, [], opts)
501 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
501 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
502 match, prefix, subrepos=opts.get('subrepos'))
502 match, prefix, subrepos=opts.get('subrepos'))
503
503
504 @command('backout',
504 @command('backout',
505 [('', 'merge', None, _('merge with old dirstate parent after backout')),
505 [('', 'merge', None, _('merge with old dirstate parent after backout')),
506 ('', 'commit', None,
506 ('', 'commit', None,
507 _('commit if no conflicts were encountered (DEPRECATED)')),
507 _('commit if no conflicts were encountered (DEPRECATED)')),
508 ('', 'no-commit', None, _('do not commit')),
508 ('', 'no-commit', None, _('do not commit')),
509 ('', 'parent', '',
509 ('', 'parent', '',
510 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
510 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
511 ('r', 'rev', '', _('revision to backout'), _('REV')),
511 ('r', 'rev', '', _('revision to backout'), _('REV')),
512 ('e', 'edit', False, _('invoke editor on commit messages')),
512 ('e', 'edit', False, _('invoke editor on commit messages')),
513 ] + mergetoolopts + walkopts + commitopts + commitopts2,
513 ] + mergetoolopts + walkopts + commitopts + commitopts2,
514 _('[OPTION]... [-r] REV'))
514 _('[OPTION]... [-r] REV'))
515 def backout(ui, repo, node=None, rev=None, **opts):
515 def backout(ui, repo, node=None, rev=None, **opts):
516 '''reverse effect of earlier changeset
516 '''reverse effect of earlier changeset
517
517
518 Prepare a new changeset with the effect of REV undone in the
518 Prepare a new changeset with the effect of REV undone in the
519 current working directory. If no conflicts were encountered,
519 current working directory. If no conflicts were encountered,
520 it will be committed immediately.
520 it will be committed immediately.
521
521
522 If REV is the parent of the working directory, then this new changeset
522 If REV is the parent of the working directory, then this new changeset
523 is committed automatically (unless --no-commit is specified).
523 is committed automatically (unless --no-commit is specified).
524
524
525 .. note::
525 .. note::
526
526
527 :hg:`backout` cannot be used to fix either an unwanted or
527 :hg:`backout` cannot be used to fix either an unwanted or
528 incorrect merge.
528 incorrect merge.
529
529
530 .. container:: verbose
530 .. container:: verbose
531
531
532 Examples:
532 Examples:
533
533
534 - Reverse the effect of the parent of the working directory.
534 - Reverse the effect of the parent of the working directory.
535 This backout will be committed immediately::
535 This backout will be committed immediately::
536
536
537 hg backout -r .
537 hg backout -r .
538
538
539 - Reverse the effect of previous bad revision 23::
539 - Reverse the effect of previous bad revision 23::
540
540
541 hg backout -r 23
541 hg backout -r 23
542
542
543 - Reverse the effect of previous bad revision 23 and
543 - Reverse the effect of previous bad revision 23 and
544 leave changes uncommitted::
544 leave changes uncommitted::
545
545
546 hg backout -r 23 --no-commit
546 hg backout -r 23 --no-commit
547 hg commit -m "Backout revision 23"
547 hg commit -m "Backout revision 23"
548
548
549 By default, the pending changeset will have one parent,
549 By default, the pending changeset will have one parent,
550 maintaining a linear history. With --merge, the pending
550 maintaining a linear history. With --merge, the pending
551 changeset will instead have two parents: the old parent of the
551 changeset will instead have two parents: the old parent of the
552 working directory and a new child of REV that simply undoes REV.
552 working directory and a new child of REV that simply undoes REV.
553
553
554 Before version 1.7, the behavior without --merge was equivalent
554 Before version 1.7, the behavior without --merge was equivalent
555 to specifying --merge followed by :hg:`update --clean .` to
555 to specifying --merge followed by :hg:`update --clean .` to
556 cancel the merge and leave the child of REV as a head to be
556 cancel the merge and leave the child of REV as a head to be
557 merged separately.
557 merged separately.
558
558
559 See :hg:`help dates` for a list of formats valid for -d/--date.
559 See :hg:`help dates` for a list of formats valid for -d/--date.
560
560
561 See :hg:`help revert` for a way to restore files to the state
561 See :hg:`help revert` for a way to restore files to the state
562 of another revision.
562 of another revision.
563
563
564 Returns 0 on success, 1 if nothing to backout or there are unresolved
564 Returns 0 on success, 1 if nothing to backout or there are unresolved
565 files.
565 files.
566 '''
566 '''
567 wlock = lock = None
567 wlock = lock = None
568 try:
568 try:
569 wlock = repo.wlock()
569 wlock = repo.wlock()
570 lock = repo.lock()
570 lock = repo.lock()
571 return _dobackout(ui, repo, node, rev, **opts)
571 return _dobackout(ui, repo, node, rev, **opts)
572 finally:
572 finally:
573 release(lock, wlock)
573 release(lock, wlock)
574
574
575 def _dobackout(ui, repo, node=None, rev=None, **opts):
575 def _dobackout(ui, repo, node=None, rev=None, **opts):
576 opts = pycompat.byteskwargs(opts)
576 opts = pycompat.byteskwargs(opts)
577 if opts.get('commit') and opts.get('no_commit'):
577 if opts.get('commit') and opts.get('no_commit'):
578 raise error.Abort(_("cannot use --commit with --no-commit"))
578 raise error.Abort(_("cannot use --commit with --no-commit"))
579 if opts.get('merge') and opts.get('no_commit'):
579 if opts.get('merge') and opts.get('no_commit'):
580 raise error.Abort(_("cannot use --merge with --no-commit"))
580 raise error.Abort(_("cannot use --merge with --no-commit"))
581
581
582 if rev and node:
582 if rev and node:
583 raise error.Abort(_("please specify just one revision"))
583 raise error.Abort(_("please specify just one revision"))
584
584
585 if not rev:
585 if not rev:
586 rev = node
586 rev = node
587
587
588 if not rev:
588 if not rev:
589 raise error.Abort(_("please specify a revision to backout"))
589 raise error.Abort(_("please specify a revision to backout"))
590
590
591 date = opts.get('date')
591 date = opts.get('date')
592 if date:
592 if date:
593 opts['date'] = dateutil.parsedate(date)
593 opts['date'] = dateutil.parsedate(date)
594
594
595 cmdutil.checkunfinished(repo)
595 cmdutil.checkunfinished(repo)
596 cmdutil.bailifchanged(repo)
596 cmdutil.bailifchanged(repo)
597 node = scmutil.revsingle(repo, rev).node()
597 node = scmutil.revsingle(repo, rev).node()
598
598
599 op1, op2 = repo.dirstate.parents()
599 op1, op2 = repo.dirstate.parents()
600 if not repo.changelog.isancestor(node, op1):
600 if not repo.changelog.isancestor(node, op1):
601 raise error.Abort(_('cannot backout change that is not an ancestor'))
601 raise error.Abort(_('cannot backout change that is not an ancestor'))
602
602
603 p1, p2 = repo.changelog.parents(node)
603 p1, p2 = repo.changelog.parents(node)
604 if p1 == nullid:
604 if p1 == nullid:
605 raise error.Abort(_('cannot backout a change with no parents'))
605 raise error.Abort(_('cannot backout a change with no parents'))
606 if p2 != nullid:
606 if p2 != nullid:
607 if not opts.get('parent'):
607 if not opts.get('parent'):
608 raise error.Abort(_('cannot backout a merge changeset'))
608 raise error.Abort(_('cannot backout a merge changeset'))
609 p = repo.lookup(opts['parent'])
609 p = repo.lookup(opts['parent'])
610 if p not in (p1, p2):
610 if p not in (p1, p2):
611 raise error.Abort(_('%s is not a parent of %s') %
611 raise error.Abort(_('%s is not a parent of %s') %
612 (short(p), short(node)))
612 (short(p), short(node)))
613 parent = p
613 parent = p
614 else:
614 else:
615 if opts.get('parent'):
615 if opts.get('parent'):
616 raise error.Abort(_('cannot use --parent on non-merge changeset'))
616 raise error.Abort(_('cannot use --parent on non-merge changeset'))
617 parent = p1
617 parent = p1
618
618
619 # the backout should appear on the same branch
619 # the backout should appear on the same branch
620 branch = repo.dirstate.branch()
620 branch = repo.dirstate.branch()
621 bheads = repo.branchheads(branch)
621 bheads = repo.branchheads(branch)
622 rctx = scmutil.revsingle(repo, hex(parent))
622 rctx = scmutil.revsingle(repo, hex(parent))
623 if not opts.get('merge') and op1 != node:
623 if not opts.get('merge') and op1 != node:
624 dsguard = dirstateguard.dirstateguard(repo, 'backout')
624 dsguard = dirstateguard.dirstateguard(repo, 'backout')
625 try:
625 try:
626 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
626 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
627 'backout')
627 'backout')
628 stats = mergemod.update(repo, parent, True, True, node, False)
628 stats = mergemod.update(repo, parent, True, True, node, False)
629 repo.setparents(op1, op2)
629 repo.setparents(op1, op2)
630 dsguard.close()
630 dsguard.close()
631 hg._showstats(repo, stats)
631 hg._showstats(repo, stats)
632 if stats.unresolvedcount:
632 if stats.unresolvedcount:
633 repo.ui.status(_("use 'hg resolve' to retry unresolved "
633 repo.ui.status(_("use 'hg resolve' to retry unresolved "
634 "file merges\n"))
634 "file merges\n"))
635 return 1
635 return 1
636 finally:
636 finally:
637 ui.setconfig('ui', 'forcemerge', '', '')
637 ui.setconfig('ui', 'forcemerge', '', '')
638 lockmod.release(dsguard)
638 lockmod.release(dsguard)
639 else:
639 else:
640 hg.clean(repo, node, show_stats=False)
640 hg.clean(repo, node, show_stats=False)
641 repo.dirstate.setbranch(branch)
641 repo.dirstate.setbranch(branch)
642 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
642 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
643
643
644 if opts.get('no_commit'):
644 if opts.get('no_commit'):
645 msg = _("changeset %s backed out, "
645 msg = _("changeset %s backed out, "
646 "don't forget to commit.\n")
646 "don't forget to commit.\n")
647 ui.status(msg % short(node))
647 ui.status(msg % short(node))
648 return 0
648 return 0
649
649
650 def commitfunc(ui, repo, message, match, opts):
650 def commitfunc(ui, repo, message, match, opts):
651 editform = 'backout'
651 editform = 'backout'
652 e = cmdutil.getcommiteditor(editform=editform,
652 e = cmdutil.getcommiteditor(editform=editform,
653 **pycompat.strkwargs(opts))
653 **pycompat.strkwargs(opts))
654 if not message:
654 if not message:
655 # we don't translate commit messages
655 # we don't translate commit messages
656 message = "Backed out changeset %s" % short(node)
656 message = "Backed out changeset %s" % short(node)
657 e = cmdutil.getcommiteditor(edit=True, editform=editform)
657 e = cmdutil.getcommiteditor(edit=True, editform=editform)
658 return repo.commit(message, opts.get('user'), opts.get('date'),
658 return repo.commit(message, opts.get('user'), opts.get('date'),
659 match, editor=e)
659 match, editor=e)
660 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
660 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
661 if not newnode:
661 if not newnode:
662 ui.status(_("nothing changed\n"))
662 ui.status(_("nothing changed\n"))
663 return 1
663 return 1
664 cmdutil.commitstatus(repo, newnode, branch, bheads)
664 cmdutil.commitstatus(repo, newnode, branch, bheads)
665
665
666 def nice(node):
666 def nice(node):
667 return '%d:%s' % (repo.changelog.rev(node), short(node))
667 return '%d:%s' % (repo.changelog.rev(node), short(node))
668 ui.status(_('changeset %s backs out changeset %s\n') %
668 ui.status(_('changeset %s backs out changeset %s\n') %
669 (nice(repo.changelog.tip()), nice(node)))
669 (nice(repo.changelog.tip()), nice(node)))
670 if opts.get('merge') and op1 != node:
670 if opts.get('merge') and op1 != node:
671 hg.clean(repo, op1, show_stats=False)
671 hg.clean(repo, op1, show_stats=False)
672 ui.status(_('merging with changeset %s\n')
672 ui.status(_('merging with changeset %s\n')
673 % nice(repo.changelog.tip()))
673 % nice(repo.changelog.tip()))
674 try:
674 try:
675 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
675 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
676 'backout')
676 'backout')
677 return hg.merge(repo, hex(repo.changelog.tip()))
677 return hg.merge(repo, hex(repo.changelog.tip()))
678 finally:
678 finally:
679 ui.setconfig('ui', 'forcemerge', '', '')
679 ui.setconfig('ui', 'forcemerge', '', '')
680 return 0
680 return 0
681
681
682 @command('bisect',
682 @command('bisect',
683 [('r', 'reset', False, _('reset bisect state')),
683 [('r', 'reset', False, _('reset bisect state')),
684 ('g', 'good', False, _('mark changeset good')),
684 ('g', 'good', False, _('mark changeset good')),
685 ('b', 'bad', False, _('mark changeset bad')),
685 ('b', 'bad', False, _('mark changeset bad')),
686 ('s', 'skip', False, _('skip testing changeset')),
686 ('s', 'skip', False, _('skip testing changeset')),
687 ('e', 'extend', False, _('extend the bisect range')),
687 ('e', 'extend', False, _('extend the bisect range')),
688 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
688 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
689 ('U', 'noupdate', False, _('do not update to target'))],
689 ('U', 'noupdate', False, _('do not update to target'))],
690 _("[-gbsr] [-U] [-c CMD] [REV]"))
690 _("[-gbsr] [-U] [-c CMD] [REV]"))
691 def bisect(ui, repo, rev=None, extra=None, command=None,
691 def bisect(ui, repo, rev=None, extra=None, command=None,
692 reset=None, good=None, bad=None, skip=None, extend=None,
692 reset=None, good=None, bad=None, skip=None, extend=None,
693 noupdate=None):
693 noupdate=None):
694 """subdivision search of changesets
694 """subdivision search of changesets
695
695
696 This command helps to find changesets which introduce problems. To
696 This command helps to find changesets which introduce problems. To
697 use, mark the earliest changeset you know exhibits the problem as
697 use, mark the earliest changeset you know exhibits the problem as
698 bad, then mark the latest changeset which is free from the problem
698 bad, then mark the latest changeset which is free from the problem
699 as good. Bisect will update your working directory to a revision
699 as good. Bisect will update your working directory to a revision
700 for testing (unless the -U/--noupdate option is specified). Once
700 for testing (unless the -U/--noupdate option is specified). Once
701 you have performed tests, mark the working directory as good or
701 you have performed tests, mark the working directory as good or
702 bad, and bisect will either update to another candidate changeset
702 bad, and bisect will either update to another candidate changeset
703 or announce that it has found the bad revision.
703 or announce that it has found the bad revision.
704
704
705 As a shortcut, you can also use the revision argument to mark a
705 As a shortcut, you can also use the revision argument to mark a
706 revision as good or bad without checking it out first.
706 revision as good or bad without checking it out first.
707
707
708 If you supply a command, it will be used for automatic bisection.
708 If you supply a command, it will be used for automatic bisection.
709 The environment variable HG_NODE will contain the ID of the
709 The environment variable HG_NODE will contain the ID of the
710 changeset being tested. The exit status of the command will be
710 changeset being tested. The exit status of the command will be
711 used to mark revisions as good or bad: status 0 means good, 125
711 used to mark revisions as good or bad: status 0 means good, 125
712 means to skip the revision, 127 (command not found) will abort the
712 means to skip the revision, 127 (command not found) will abort the
713 bisection, and any other non-zero exit status means the revision
713 bisection, and any other non-zero exit status means the revision
714 is bad.
714 is bad.
715
715
716 .. container:: verbose
716 .. container:: verbose
717
717
718 Some examples:
718 Some examples:
719
719
720 - start a bisection with known bad revision 34, and good revision 12::
720 - start a bisection with known bad revision 34, and good revision 12::
721
721
722 hg bisect --bad 34
722 hg bisect --bad 34
723 hg bisect --good 12
723 hg bisect --good 12
724
724
725 - advance the current bisection by marking current revision as good or
725 - advance the current bisection by marking current revision as good or
726 bad::
726 bad::
727
727
728 hg bisect --good
728 hg bisect --good
729 hg bisect --bad
729 hg bisect --bad
730
730
731 - mark the current revision, or a known revision, to be skipped (e.g. if
731 - mark the current revision, or a known revision, to be skipped (e.g. if
732 that revision is not usable because of another issue)::
732 that revision is not usable because of another issue)::
733
733
734 hg bisect --skip
734 hg bisect --skip
735 hg bisect --skip 23
735 hg bisect --skip 23
736
736
737 - skip all revisions that do not touch directories ``foo`` or ``bar``::
737 - skip all revisions that do not touch directories ``foo`` or ``bar``::
738
738
739 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
739 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
740
740
741 - forget the current bisection::
741 - forget the current bisection::
742
742
743 hg bisect --reset
743 hg bisect --reset
744
744
745 - use 'make && make tests' to automatically find the first broken
745 - use 'make && make tests' to automatically find the first broken
746 revision::
746 revision::
747
747
748 hg bisect --reset
748 hg bisect --reset
749 hg bisect --bad 34
749 hg bisect --bad 34
750 hg bisect --good 12
750 hg bisect --good 12
751 hg bisect --command "make && make tests"
751 hg bisect --command "make && make tests"
752
752
753 - see all changesets whose states are already known in the current
753 - see all changesets whose states are already known in the current
754 bisection::
754 bisection::
755
755
756 hg log -r "bisect(pruned)"
756 hg log -r "bisect(pruned)"
757
757
758 - see the changeset currently being bisected (especially useful
758 - see the changeset currently being bisected (especially useful
759 if running with -U/--noupdate)::
759 if running with -U/--noupdate)::
760
760
761 hg log -r "bisect(current)"
761 hg log -r "bisect(current)"
762
762
763 - see all changesets that took part in the current bisection::
763 - see all changesets that took part in the current bisection::
764
764
765 hg log -r "bisect(range)"
765 hg log -r "bisect(range)"
766
766
767 - you can even get a nice graph::
767 - you can even get a nice graph::
768
768
769 hg log --graph -r "bisect(range)"
769 hg log --graph -r "bisect(range)"
770
770
771 See :hg:`help revisions.bisect` for more about the `bisect()` predicate.
771 See :hg:`help revisions.bisect` for more about the `bisect()` predicate.
772
772
773 Returns 0 on success.
773 Returns 0 on success.
774 """
774 """
775 # backward compatibility
775 # backward compatibility
776 if rev in "good bad reset init".split():
776 if rev in "good bad reset init".split():
777 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
777 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
778 cmd, rev, extra = rev, extra, None
778 cmd, rev, extra = rev, extra, None
779 if cmd == "good":
779 if cmd == "good":
780 good = True
780 good = True
781 elif cmd == "bad":
781 elif cmd == "bad":
782 bad = True
782 bad = True
783 else:
783 else:
784 reset = True
784 reset = True
785 elif extra:
785 elif extra:
786 raise error.Abort(_('incompatible arguments'))
786 raise error.Abort(_('incompatible arguments'))
787
787
788 incompatibles = {
788 incompatibles = {
789 '--bad': bad,
789 '--bad': bad,
790 '--command': bool(command),
790 '--command': bool(command),
791 '--extend': extend,
791 '--extend': extend,
792 '--good': good,
792 '--good': good,
793 '--reset': reset,
793 '--reset': reset,
794 '--skip': skip,
794 '--skip': skip,
795 }
795 }
796
796
797 enabled = [x for x in incompatibles if incompatibles[x]]
797 enabled = [x for x in incompatibles if incompatibles[x]]
798
798
799 if len(enabled) > 1:
799 if len(enabled) > 1:
800 raise error.Abort(_('%s and %s are incompatible') %
800 raise error.Abort(_('%s and %s are incompatible') %
801 tuple(sorted(enabled)[0:2]))
801 tuple(sorted(enabled)[0:2]))
802
802
803 if reset:
803 if reset:
804 hbisect.resetstate(repo)
804 hbisect.resetstate(repo)
805 return
805 return
806
806
807 state = hbisect.load_state(repo)
807 state = hbisect.load_state(repo)
808
808
809 # update state
809 # update state
810 if good or bad or skip:
810 if good or bad or skip:
811 if rev:
811 if rev:
812 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
812 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
813 else:
813 else:
814 nodes = [repo.lookup('.')]
814 nodes = [repo.lookup('.')]
815 if good:
815 if good:
816 state['good'] += nodes
816 state['good'] += nodes
817 elif bad:
817 elif bad:
818 state['bad'] += nodes
818 state['bad'] += nodes
819 elif skip:
819 elif skip:
820 state['skip'] += nodes
820 state['skip'] += nodes
821 hbisect.save_state(repo, state)
821 hbisect.save_state(repo, state)
822 if not (state['good'] and state['bad']):
822 if not (state['good'] and state['bad']):
823 return
823 return
824
824
825 def mayupdate(repo, node, show_stats=True):
825 def mayupdate(repo, node, show_stats=True):
826 """common used update sequence"""
826 """common used update sequence"""
827 if noupdate:
827 if noupdate:
828 return
828 return
829 cmdutil.checkunfinished(repo)
829 cmdutil.checkunfinished(repo)
830 cmdutil.bailifchanged(repo)
830 cmdutil.bailifchanged(repo)
831 return hg.clean(repo, node, show_stats=show_stats)
831 return hg.clean(repo, node, show_stats=show_stats)
832
832
833 displayer = logcmdutil.changesetdisplayer(ui, repo, {})
833 displayer = logcmdutil.changesetdisplayer(ui, repo, {})
834
834
835 if command:
835 if command:
836 changesets = 1
836 changesets = 1
837 if noupdate:
837 if noupdate:
838 try:
838 try:
839 node = state['current'][0]
839 node = state['current'][0]
840 except LookupError:
840 except LookupError:
841 raise error.Abort(_('current bisect revision is unknown - '
841 raise error.Abort(_('current bisect revision is unknown - '
842 'start a new bisect to fix'))
842 'start a new bisect to fix'))
843 else:
843 else:
844 node, p2 = repo.dirstate.parents()
844 node, p2 = repo.dirstate.parents()
845 if p2 != nullid:
845 if p2 != nullid:
846 raise error.Abort(_('current bisect revision is a merge'))
846 raise error.Abort(_('current bisect revision is a merge'))
847 if rev:
847 if rev:
848 node = repo[scmutil.revsingle(repo, rev, node)].node()
848 node = repo[scmutil.revsingle(repo, rev, node)].node()
849 try:
849 try:
850 while changesets:
850 while changesets:
851 # update state
851 # update state
852 state['current'] = [node]
852 state['current'] = [node]
853 hbisect.save_state(repo, state)
853 hbisect.save_state(repo, state)
854 status = ui.system(command, environ={'HG_NODE': hex(node)},
854 status = ui.system(command, environ={'HG_NODE': hex(node)},
855 blockedtag='bisect_check')
855 blockedtag='bisect_check')
856 if status == 125:
856 if status == 125:
857 transition = "skip"
857 transition = "skip"
858 elif status == 0:
858 elif status == 0:
859 transition = "good"
859 transition = "good"
860 # status < 0 means process was killed
860 # status < 0 means process was killed
861 elif status == 127:
861 elif status == 127:
862 raise error.Abort(_("failed to execute %s") % command)
862 raise error.Abort(_("failed to execute %s") % command)
863 elif status < 0:
863 elif status < 0:
864 raise error.Abort(_("%s killed") % command)
864 raise error.Abort(_("%s killed") % command)
865 else:
865 else:
866 transition = "bad"
866 transition = "bad"
867 state[transition].append(node)
867 state[transition].append(node)
868 ctx = repo[node]
868 ctx = repo[node]
869 ui.status(_('changeset %d:%s: %s\n') % (ctx.rev(), ctx,
869 ui.status(_('changeset %d:%s: %s\n') % (ctx.rev(), ctx,
870 transition))
870 transition))
871 hbisect.checkstate(state)
871 hbisect.checkstate(state)
872 # bisect
872 # bisect
873 nodes, changesets, bgood = hbisect.bisect(repo, state)
873 nodes, changesets, bgood = hbisect.bisect(repo, state)
874 # update to next check
874 # update to next check
875 node = nodes[0]
875 node = nodes[0]
876 mayupdate(repo, node, show_stats=False)
876 mayupdate(repo, node, show_stats=False)
877 finally:
877 finally:
878 state['current'] = [node]
878 state['current'] = [node]
879 hbisect.save_state(repo, state)
879 hbisect.save_state(repo, state)
880 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
880 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
881 return
881 return
882
882
883 hbisect.checkstate(state)
883 hbisect.checkstate(state)
884
884
885 # actually bisect
885 # actually bisect
886 nodes, changesets, good = hbisect.bisect(repo, state)
886 nodes, changesets, good = hbisect.bisect(repo, state)
887 if extend:
887 if extend:
888 if not changesets:
888 if not changesets:
889 extendnode = hbisect.extendrange(repo, state, nodes, good)
889 extendnode = hbisect.extendrange(repo, state, nodes, good)
890 if extendnode is not None:
890 if extendnode is not None:
891 ui.write(_("Extending search to changeset %d:%s\n")
891 ui.write(_("Extending search to changeset %d:%s\n")
892 % (extendnode.rev(), extendnode))
892 % (extendnode.rev(), extendnode))
893 state['current'] = [extendnode.node()]
893 state['current'] = [extendnode.node()]
894 hbisect.save_state(repo, state)
894 hbisect.save_state(repo, state)
895 return mayupdate(repo, extendnode.node())
895 return mayupdate(repo, extendnode.node())
896 raise error.Abort(_("nothing to extend"))
896 raise error.Abort(_("nothing to extend"))
897
897
898 if changesets == 0:
898 if changesets == 0:
899 hbisect.printresult(ui, repo, state, displayer, nodes, good)
899 hbisect.printresult(ui, repo, state, displayer, nodes, good)
900 else:
900 else:
901 assert len(nodes) == 1 # only a single node can be tested next
901 assert len(nodes) == 1 # only a single node can be tested next
902 node = nodes[0]
902 node = nodes[0]
903 # compute the approximate number of remaining tests
903 # compute the approximate number of remaining tests
904 tests, size = 0, 2
904 tests, size = 0, 2
905 while size <= changesets:
905 while size <= changesets:
906 tests, size = tests + 1, size * 2
906 tests, size = tests + 1, size * 2
907 rev = repo.changelog.rev(node)
907 rev = repo.changelog.rev(node)
908 ui.write(_("Testing changeset %d:%s "
908 ui.write(_("Testing changeset %d:%s "
909 "(%d changesets remaining, ~%d tests)\n")
909 "(%d changesets remaining, ~%d tests)\n")
910 % (rev, short(node), changesets, tests))
910 % (rev, short(node), changesets, tests))
911 state['current'] = [node]
911 state['current'] = [node]
912 hbisect.save_state(repo, state)
912 hbisect.save_state(repo, state)
913 return mayupdate(repo, node)
913 return mayupdate(repo, node)
914
914
915 @command('bookmarks|bookmark',
915 @command('bookmarks|bookmark',
916 [('f', 'force', False, _('force')),
916 [('f', 'force', False, _('force')),
917 ('r', 'rev', '', _('revision for bookmark action'), _('REV')),
917 ('r', 'rev', '', _('revision for bookmark action'), _('REV')),
918 ('d', 'delete', False, _('delete a given bookmark')),
918 ('d', 'delete', False, _('delete a given bookmark')),
919 ('m', 'rename', '', _('rename a given bookmark'), _('OLD')),
919 ('m', 'rename', '', _('rename a given bookmark'), _('OLD')),
920 ('i', 'inactive', False, _('mark a bookmark inactive')),
920 ('i', 'inactive', False, _('mark a bookmark inactive')),
921 ] + formatteropts,
921 ] + formatteropts,
922 _('hg bookmarks [OPTIONS]... [NAME]...'))
922 _('hg bookmarks [OPTIONS]... [NAME]...'))
923 def bookmark(ui, repo, *names, **opts):
923 def bookmark(ui, repo, *names, **opts):
924 '''create a new bookmark or list existing bookmarks
924 '''create a new bookmark or list existing bookmarks
925
925
926 Bookmarks are labels on changesets to help track lines of development.
926 Bookmarks are labels on changesets to help track lines of development.
927 Bookmarks are unversioned and can be moved, renamed and deleted.
927 Bookmarks are unversioned and can be moved, renamed and deleted.
928 Deleting or moving a bookmark has no effect on the associated changesets.
928 Deleting or moving a bookmark has no effect on the associated changesets.
929
929
930 Creating or updating to a bookmark causes it to be marked as 'active'.
930 Creating or updating to a bookmark causes it to be marked as 'active'.
931 The active bookmark is indicated with a '*'.
931 The active bookmark is indicated with a '*'.
932 When a commit is made, the active bookmark will advance to the new commit.
932 When a commit is made, the active bookmark will advance to the new commit.
933 A plain :hg:`update` will also advance an active bookmark, if possible.
933 A plain :hg:`update` will also advance an active bookmark, if possible.
934 Updating away from a bookmark will cause it to be deactivated.
934 Updating away from a bookmark will cause it to be deactivated.
935
935
936 Bookmarks can be pushed and pulled between repositories (see
936 Bookmarks can be pushed and pulled between repositories (see
937 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
937 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
938 diverged, a new 'divergent bookmark' of the form 'name@path' will
938 diverged, a new 'divergent bookmark' of the form 'name@path' will
939 be created. Using :hg:`merge` will resolve the divergence.
939 be created. Using :hg:`merge` will resolve the divergence.
940
940
941 Specifying bookmark as '.' to -m or -d options is equivalent to specifying
941 Specifying bookmark as '.' to -m or -d options is equivalent to specifying
942 the active bookmark's name.
942 the active bookmark's name.
943
943
944 A bookmark named '@' has the special property that :hg:`clone` will
944 A bookmark named '@' has the special property that :hg:`clone` will
945 check it out by default if it exists.
945 check it out by default if it exists.
946
946
947 .. container:: verbose
947 .. container:: verbose
948
948
949 Examples:
949 Examples:
950
950
951 - create an active bookmark for a new line of development::
951 - create an active bookmark for a new line of development::
952
952
953 hg book new-feature
953 hg book new-feature
954
954
955 - create an inactive bookmark as a place marker::
955 - create an inactive bookmark as a place marker::
956
956
957 hg book -i reviewed
957 hg book -i reviewed
958
958
959 - create an inactive bookmark on another changeset::
959 - create an inactive bookmark on another changeset::
960
960
961 hg book -r .^ tested
961 hg book -r .^ tested
962
962
963 - rename bookmark turkey to dinner::
963 - rename bookmark turkey to dinner::
964
964
965 hg book -m turkey dinner
965 hg book -m turkey dinner
966
966
967 - move the '@' bookmark from another branch::
967 - move the '@' bookmark from another branch::
968
968
969 hg book -f @
969 hg book -f @
970 '''
970 '''
971 force = opts.get(r'force')
971 force = opts.get(r'force')
972 rev = opts.get(r'rev')
972 rev = opts.get(r'rev')
973 delete = opts.get(r'delete')
973 delete = opts.get(r'delete')
974 rename = opts.get(r'rename')
974 rename = opts.get(r'rename')
975 inactive = opts.get(r'inactive')
975 inactive = opts.get(r'inactive')
976
976
977 if delete and rename:
977 if delete and rename:
978 raise error.Abort(_("--delete and --rename are incompatible"))
978 raise error.Abort(_("--delete and --rename are incompatible"))
979 if delete and rev:
979 if delete and rev:
980 raise error.Abort(_("--rev is incompatible with --delete"))
980 raise error.Abort(_("--rev is incompatible with --delete"))
981 if rename and rev:
981 if rename and rev:
982 raise error.Abort(_("--rev is incompatible with --rename"))
982 raise error.Abort(_("--rev is incompatible with --rename"))
983 if not names and (delete or rev):
983 if not names and (delete or rev):
984 raise error.Abort(_("bookmark name required"))
984 raise error.Abort(_("bookmark name required"))
985
985
986 if delete or rename or names or inactive:
986 if delete or rename or names or inactive:
987 with repo.wlock(), repo.lock(), repo.transaction('bookmark') as tr:
987 with repo.wlock(), repo.lock(), repo.transaction('bookmark') as tr:
988 if delete:
988 if delete:
989 names = pycompat.maplist(repo._bookmarks.expandname, names)
989 names = pycompat.maplist(repo._bookmarks.expandname, names)
990 bookmarks.delete(repo, tr, names)
990 bookmarks.delete(repo, tr, names)
991 elif rename:
991 elif rename:
992 if not names:
992 if not names:
993 raise error.Abort(_("new bookmark name required"))
993 raise error.Abort(_("new bookmark name required"))
994 elif len(names) > 1:
994 elif len(names) > 1:
995 raise error.Abort(_("only one new bookmark name allowed"))
995 raise error.Abort(_("only one new bookmark name allowed"))
996 rename = repo._bookmarks.expandname(rename)
996 rename = repo._bookmarks.expandname(rename)
997 bookmarks.rename(repo, tr, rename, names[0], force, inactive)
997 bookmarks.rename(repo, tr, rename, names[0], force, inactive)
998 elif names:
998 elif names:
999 bookmarks.addbookmarks(repo, tr, names, rev, force, inactive)
999 bookmarks.addbookmarks(repo, tr, names, rev, force, inactive)
1000 elif inactive:
1000 elif inactive:
1001 if len(repo._bookmarks) == 0:
1001 if len(repo._bookmarks) == 0:
1002 ui.status(_("no bookmarks set\n"))
1002 ui.status(_("no bookmarks set\n"))
1003 elif not repo._activebookmark:
1003 elif not repo._activebookmark:
1004 ui.status(_("no active bookmark\n"))
1004 ui.status(_("no active bookmark\n"))
1005 else:
1005 else:
1006 bookmarks.deactivate(repo)
1006 bookmarks.deactivate(repo)
1007 else: # show bookmarks
1007 else: # show bookmarks
1008 bookmarks.printbookmarks(ui, repo, **opts)
1008 bookmarks.printbookmarks(ui, repo, **opts)
1009
1009
1010 @command('branch',
1010 @command('branch',
1011 [('f', 'force', None,
1011 [('f', 'force', None,
1012 _('set branch name even if it shadows an existing branch')),
1012 _('set branch name even if it shadows an existing branch')),
1013 ('C', 'clean', None, _('reset branch name to parent branch name')),
1013 ('C', 'clean', None, _('reset branch name to parent branch name')),
1014 ('r', 'rev', [], _('change branches of the given revs (EXPERIMENTAL)')),
1014 ('r', 'rev', [], _('change branches of the given revs (EXPERIMENTAL)')),
1015 ],
1015 ],
1016 _('[-fC] [NAME]'))
1016 _('[-fC] [NAME]'))
1017 def branch(ui, repo, label=None, **opts):
1017 def branch(ui, repo, label=None, **opts):
1018 """set or show the current branch name
1018 """set or show the current branch name
1019
1019
1020 .. note::
1020 .. note::
1021
1021
1022 Branch names are permanent and global. Use :hg:`bookmark` to create a
1022 Branch names are permanent and global. Use :hg:`bookmark` to create a
1023 light-weight bookmark instead. See :hg:`help glossary` for more
1023 light-weight bookmark instead. See :hg:`help glossary` for more
1024 information about named branches and bookmarks.
1024 information about named branches and bookmarks.
1025
1025
1026 With no argument, show the current branch name. With one argument,
1026 With no argument, show the current branch name. With one argument,
1027 set the working directory branch name (the branch will not exist
1027 set the working directory branch name (the branch will not exist
1028 in the repository until the next commit). Standard practice
1028 in the repository until the next commit). Standard practice
1029 recommends that primary development take place on the 'default'
1029 recommends that primary development take place on the 'default'
1030 branch.
1030 branch.
1031
1031
1032 Unless -f/--force is specified, branch will not let you set a
1032 Unless -f/--force is specified, branch will not let you set a
1033 branch name that already exists.
1033 branch name that already exists.
1034
1034
1035 Use -C/--clean to reset the working directory branch to that of
1035 Use -C/--clean to reset the working directory branch to that of
1036 the parent of the working directory, negating a previous branch
1036 the parent of the working directory, negating a previous branch
1037 change.
1037 change.
1038
1038
1039 Use the command :hg:`update` to switch to an existing branch. Use
1039 Use the command :hg:`update` to switch to an existing branch. Use
1040 :hg:`commit --close-branch` to mark this branch head as closed.
1040 :hg:`commit --close-branch` to mark this branch head as closed.
1041 When all heads of a branch are closed, the branch will be
1041 When all heads of a branch are closed, the branch will be
1042 considered closed.
1042 considered closed.
1043
1043
1044 Returns 0 on success.
1044 Returns 0 on success.
1045 """
1045 """
1046 opts = pycompat.byteskwargs(opts)
1046 opts = pycompat.byteskwargs(opts)
1047 revs = opts.get('rev')
1047 revs = opts.get('rev')
1048 if label:
1048 if label:
1049 label = label.strip()
1049 label = label.strip()
1050
1050
1051 if not opts.get('clean') and not label:
1051 if not opts.get('clean') and not label:
1052 if revs:
1052 if revs:
1053 raise error.Abort(_("no branch name specified for the revisions"))
1053 raise error.Abort(_("no branch name specified for the revisions"))
1054 ui.write("%s\n" % repo.dirstate.branch())
1054 ui.write("%s\n" % repo.dirstate.branch())
1055 return
1055 return
1056
1056
1057 with repo.wlock():
1057 with repo.wlock():
1058 if opts.get('clean'):
1058 if opts.get('clean'):
1059 label = repo[None].p1().branch()
1059 label = repo[None].p1().branch()
1060 repo.dirstate.setbranch(label)
1060 repo.dirstate.setbranch(label)
1061 ui.status(_('reset working directory to branch %s\n') % label)
1061 ui.status(_('reset working directory to branch %s\n') % label)
1062 elif label:
1062 elif label:
1063
1063
1064 scmutil.checknewlabel(repo, label, 'branch')
1064 scmutil.checknewlabel(repo, label, 'branch')
1065 if revs:
1065 if revs:
1066 return cmdutil.changebranch(ui, repo, revs, label)
1066 return cmdutil.changebranch(ui, repo, revs, label)
1067
1067
1068 if not opts.get('force') and label in repo.branchmap():
1068 if not opts.get('force') and label in repo.branchmap():
1069 if label not in [p.branch() for p in repo[None].parents()]:
1069 if label not in [p.branch() for p in repo[None].parents()]:
1070 raise error.Abort(_('a branch of the same name already'
1070 raise error.Abort(_('a branch of the same name already'
1071 ' exists'),
1071 ' exists'),
1072 # i18n: "it" refers to an existing branch
1072 # i18n: "it" refers to an existing branch
1073 hint=_("use 'hg update' to switch to it"))
1073 hint=_("use 'hg update' to switch to it"))
1074
1074
1075 repo.dirstate.setbranch(label)
1075 repo.dirstate.setbranch(label)
1076 ui.status(_('marked working directory as branch %s\n') % label)
1076 ui.status(_('marked working directory as branch %s\n') % label)
1077
1077
1078 # find any open named branches aside from default
1078 # find any open named branches aside from default
1079 others = [n for n, h, t, c in repo.branchmap().iterbranches()
1079 others = [n for n, h, t, c in repo.branchmap().iterbranches()
1080 if n != "default" and not c]
1080 if n != "default" and not c]
1081 if not others:
1081 if not others:
1082 ui.status(_('(branches are permanent and global, '
1082 ui.status(_('(branches are permanent and global, '
1083 'did you want a bookmark?)\n'))
1083 'did you want a bookmark?)\n'))
1084
1084
1085 @command('branches',
1085 @command('branches',
1086 [('a', 'active', False,
1086 [('a', 'active', False,
1087 _('show only branches that have unmerged heads (DEPRECATED)')),
1087 _('show only branches that have unmerged heads (DEPRECATED)')),
1088 ('c', 'closed', False, _('show normal and closed branches')),
1088 ('c', 'closed', False, _('show normal and closed branches')),
1089 ] + formatteropts,
1089 ] + formatteropts,
1090 _('[-c]'), cmdtype=readonly)
1090 _('[-c]'), cmdtype=readonly)
1091 def branches(ui, repo, active=False, closed=False, **opts):
1091 def branches(ui, repo, active=False, closed=False, **opts):
1092 """list repository named branches
1092 """list repository named branches
1093
1093
1094 List the repository's named branches, indicating which ones are
1094 List the repository's named branches, indicating which ones are
1095 inactive. If -c/--closed is specified, also list branches which have
1095 inactive. If -c/--closed is specified, also list branches which have
1096 been marked closed (see :hg:`commit --close-branch`).
1096 been marked closed (see :hg:`commit --close-branch`).
1097
1097
1098 Use the command :hg:`update` to switch to an existing branch.
1098 Use the command :hg:`update` to switch to an existing branch.
1099
1099
1100 Returns 0.
1100 Returns 0.
1101 """
1101 """
1102
1102
1103 opts = pycompat.byteskwargs(opts)
1103 opts = pycompat.byteskwargs(opts)
1104 ui.pager('branches')
1104 ui.pager('branches')
1105 fm = ui.formatter('branches', opts)
1105 fm = ui.formatter('branches', opts)
1106 hexfunc = fm.hexfunc
1106 hexfunc = fm.hexfunc
1107
1107
1108 allheads = set(repo.heads())
1108 allheads = set(repo.heads())
1109 branches = []
1109 branches = []
1110 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1110 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1111 isactive = False
1111 isactive = False
1112 if not isclosed:
1112 if not isclosed:
1113 openheads = set(repo.branchmap().iteropen(heads))
1113 openheads = set(repo.branchmap().iteropen(heads))
1114 isactive = bool(openheads & allheads)
1114 isactive = bool(openheads & allheads)
1115 branches.append((tag, repo[tip], isactive, not isclosed))
1115 branches.append((tag, repo[tip], isactive, not isclosed))
1116 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1116 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1117 reverse=True)
1117 reverse=True)
1118
1118
1119 for tag, ctx, isactive, isopen in branches:
1119 for tag, ctx, isactive, isopen in branches:
1120 if active and not isactive:
1120 if active and not isactive:
1121 continue
1121 continue
1122 if isactive:
1122 if isactive:
1123 label = 'branches.active'
1123 label = 'branches.active'
1124 notice = ''
1124 notice = ''
1125 elif not isopen:
1125 elif not isopen:
1126 if not closed:
1126 if not closed:
1127 continue
1127 continue
1128 label = 'branches.closed'
1128 label = 'branches.closed'
1129 notice = _(' (closed)')
1129 notice = _(' (closed)')
1130 else:
1130 else:
1131 label = 'branches.inactive'
1131 label = 'branches.inactive'
1132 notice = _(' (inactive)')
1132 notice = _(' (inactive)')
1133 current = (tag == repo.dirstate.branch())
1133 current = (tag == repo.dirstate.branch())
1134 if current:
1134 if current:
1135 label = 'branches.current'
1135 label = 'branches.current'
1136
1136
1137 fm.startitem()
1137 fm.startitem()
1138 fm.write('branch', '%s', tag, label=label)
1138 fm.write('branch', '%s', tag, label=label)
1139 rev = ctx.rev()
1139 rev = ctx.rev()
1140 padsize = max(31 - len("%d" % rev) - encoding.colwidth(tag), 0)
1140 padsize = max(31 - len("%d" % rev) - encoding.colwidth(tag), 0)
1141 fmt = ' ' * padsize + ' %d:%s'
1141 fmt = ' ' * padsize + ' %d:%s'
1142 fm.condwrite(not ui.quiet, 'rev node', fmt, rev, hexfunc(ctx.node()),
1142 fm.condwrite(not ui.quiet, 'rev node', fmt, rev, hexfunc(ctx.node()),
1143 label='log.changeset changeset.%s' % ctx.phasestr())
1143 label='log.changeset changeset.%s' % ctx.phasestr())
1144 fm.context(ctx=ctx)
1144 fm.context(ctx=ctx)
1145 fm.data(active=isactive, closed=not isopen, current=current)
1145 fm.data(active=isactive, closed=not isopen, current=current)
1146 if not ui.quiet:
1146 if not ui.quiet:
1147 fm.plain(notice)
1147 fm.plain(notice)
1148 fm.plain('\n')
1148 fm.plain('\n')
1149 fm.end()
1149 fm.end()
1150
1150
1151 @command('bundle',
1151 @command('bundle',
1152 [('f', 'force', None, _('run even when the destination is unrelated')),
1152 [('f', 'force', None, _('run even when the destination is unrelated')),
1153 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1153 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1154 _('REV')),
1154 _('REV')),
1155 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1155 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1156 _('BRANCH')),
1156 _('BRANCH')),
1157 ('', 'base', [],
1157 ('', 'base', [],
1158 _('a base changeset assumed to be available at the destination'),
1158 _('a base changeset assumed to be available at the destination'),
1159 _('REV')),
1159 _('REV')),
1160 ('a', 'all', None, _('bundle all changesets in the repository')),
1160 ('a', 'all', None, _('bundle all changesets in the repository')),
1161 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1161 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1162 ] + remoteopts,
1162 ] + remoteopts,
1163 _('[-f] [-t BUNDLESPEC] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1163 _('[-f] [-t BUNDLESPEC] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1164 def bundle(ui, repo, fname, dest=None, **opts):
1164 def bundle(ui, repo, fname, dest=None, **opts):
1165 """create a bundle file
1165 """create a bundle file
1166
1166
1167 Generate a bundle file containing data to be transferred to another
1167 Generate a bundle file containing data to be transferred to another
1168 repository.
1168 repository.
1169
1169
1170 To create a bundle containing all changesets, use -a/--all
1170 To create a bundle containing all changesets, use -a/--all
1171 (or --base null). Otherwise, hg assumes the destination will have
1171 (or --base null). Otherwise, hg assumes the destination will have
1172 all the nodes you specify with --base parameters. Otherwise, hg
1172 all the nodes you specify with --base parameters. Otherwise, hg
1173 will assume the repository has all the nodes in destination, or
1173 will assume the repository has all the nodes in destination, or
1174 default-push/default if no destination is specified, where destination
1174 default-push/default if no destination is specified, where destination
1175 is the repository you provide through DEST option.
1175 is the repository you provide through DEST option.
1176
1176
1177 You can change bundle format with the -t/--type option. See
1177 You can change bundle format with the -t/--type option. See
1178 :hg:`help bundlespec` for documentation on this format. By default,
1178 :hg:`help bundlespec` for documentation on this format. By default,
1179 the most appropriate format is used and compression defaults to
1179 the most appropriate format is used and compression defaults to
1180 bzip2.
1180 bzip2.
1181
1181
1182 The bundle file can then be transferred using conventional means
1182 The bundle file can then be transferred using conventional means
1183 and applied to another repository with the unbundle or pull
1183 and applied to another repository with the unbundle or pull
1184 command. This is useful when direct push and pull are not
1184 command. This is useful when direct push and pull are not
1185 available or when exporting an entire repository is undesirable.
1185 available or when exporting an entire repository is undesirable.
1186
1186
1187 Applying bundles preserves all changeset contents including
1187 Applying bundles preserves all changeset contents including
1188 permissions, copy/rename information, and revision history.
1188 permissions, copy/rename information, and revision history.
1189
1189
1190 Returns 0 on success, 1 if no changes found.
1190 Returns 0 on success, 1 if no changes found.
1191 """
1191 """
1192 opts = pycompat.byteskwargs(opts)
1192 opts = pycompat.byteskwargs(opts)
1193 revs = None
1193 revs = None
1194 if 'rev' in opts:
1194 if 'rev' in opts:
1195 revstrings = opts['rev']
1195 revstrings = opts['rev']
1196 revs = scmutil.revrange(repo, revstrings)
1196 revs = scmutil.revrange(repo, revstrings)
1197 if revstrings and not revs:
1197 if revstrings and not revs:
1198 raise error.Abort(_('no commits to bundle'))
1198 raise error.Abort(_('no commits to bundle'))
1199
1199
1200 bundletype = opts.get('type', 'bzip2').lower()
1200 bundletype = opts.get('type', 'bzip2').lower()
1201 try:
1201 try:
1202 bundlespec = exchange.parsebundlespec(repo, bundletype, strict=False)
1202 bundlespec = exchange.parsebundlespec(repo, bundletype, strict=False)
1203 except error.UnsupportedBundleSpecification as e:
1203 except error.UnsupportedBundleSpecification as e:
1204 raise error.Abort(pycompat.bytestr(e),
1204 raise error.Abort(pycompat.bytestr(e),
1205 hint=_("see 'hg help bundlespec' for supported "
1205 hint=_("see 'hg help bundlespec' for supported "
1206 "values for --type"))
1206 "values for --type"))
1207 cgversion = bundlespec.contentopts["cg.version"]
1207 cgversion = bundlespec.contentopts["cg.version"]
1208
1208
1209 # Packed bundles are a pseudo bundle format for now.
1209 # Packed bundles are a pseudo bundle format for now.
1210 if cgversion == 's1':
1210 if cgversion == 's1':
1211 raise error.Abort(_('packed bundles cannot be produced by "hg bundle"'),
1211 raise error.Abort(_('packed bundles cannot be produced by "hg bundle"'),
1212 hint=_("use 'hg debugcreatestreamclonebundle'"))
1212 hint=_("use 'hg debugcreatestreamclonebundle'"))
1213
1213
1214 if opts.get('all'):
1214 if opts.get('all'):
1215 if dest:
1215 if dest:
1216 raise error.Abort(_("--all is incompatible with specifying "
1216 raise error.Abort(_("--all is incompatible with specifying "
1217 "a destination"))
1217 "a destination"))
1218 if opts.get('base'):
1218 if opts.get('base'):
1219 ui.warn(_("ignoring --base because --all was specified\n"))
1219 ui.warn(_("ignoring --base because --all was specified\n"))
1220 base = ['null']
1220 base = ['null']
1221 else:
1221 else:
1222 base = scmutil.revrange(repo, opts.get('base'))
1222 base = scmutil.revrange(repo, opts.get('base'))
1223 if cgversion not in changegroup.supportedoutgoingversions(repo):
1223 if cgversion not in changegroup.supportedoutgoingversions(repo):
1224 raise error.Abort(_("repository does not support bundle version %s") %
1224 raise error.Abort(_("repository does not support bundle version %s") %
1225 cgversion)
1225 cgversion)
1226
1226
1227 if base:
1227 if base:
1228 if dest:
1228 if dest:
1229 raise error.Abort(_("--base is incompatible with specifying "
1229 raise error.Abort(_("--base is incompatible with specifying "
1230 "a destination"))
1230 "a destination"))
1231 common = [repo.lookup(rev) for rev in base]
1231 common = [repo.lookup(rev) for rev in base]
1232 heads = [repo.lookup(r) for r in revs] if revs else None
1232 heads = [repo.lookup(r) for r in revs] if revs else None
1233 outgoing = discovery.outgoing(repo, common, heads)
1233 outgoing = discovery.outgoing(repo, common, heads)
1234 else:
1234 else:
1235 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1235 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1236 dest, branches = hg.parseurl(dest, opts.get('branch'))
1236 dest, branches = hg.parseurl(dest, opts.get('branch'))
1237 other = hg.peer(repo, opts, dest)
1237 other = hg.peer(repo, opts, dest)
1238 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1238 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1239 heads = revs and map(repo.lookup, revs) or revs
1239 heads = revs and map(repo.lookup, revs) or revs
1240 outgoing = discovery.findcommonoutgoing(repo, other,
1240 outgoing = discovery.findcommonoutgoing(repo, other,
1241 onlyheads=heads,
1241 onlyheads=heads,
1242 force=opts.get('force'),
1242 force=opts.get('force'),
1243 portable=True)
1243 portable=True)
1244
1244
1245 if not outgoing.missing:
1245 if not outgoing.missing:
1246 scmutil.nochangesfound(ui, repo, not base and outgoing.excluded)
1246 scmutil.nochangesfound(ui, repo, not base and outgoing.excluded)
1247 return 1
1247 return 1
1248
1248
1249 bcompression = bundlespec.compression
1249 bcompression = bundlespec.compression
1250 if cgversion == '01': #bundle1
1250 if cgversion == '01': #bundle1
1251 if bcompression is None:
1251 if bcompression is None:
1252 bcompression = 'UN'
1252 bcompression = 'UN'
1253 bversion = 'HG10' + bcompression
1253 bversion = 'HG10' + bcompression
1254 bcompression = None
1254 bcompression = None
1255 elif cgversion in ('02', '03'):
1255 elif cgversion in ('02', '03'):
1256 bversion = 'HG20'
1256 bversion = 'HG20'
1257 else:
1257 else:
1258 raise error.ProgrammingError(
1258 raise error.ProgrammingError(
1259 'bundle: unexpected changegroup version %s' % cgversion)
1259 'bundle: unexpected changegroup version %s' % cgversion)
1260
1260
1261 # TODO compression options should be derived from bundlespec parsing.
1261 # TODO compression options should be derived from bundlespec parsing.
1262 # This is a temporary hack to allow adjusting bundle compression
1262 # This is a temporary hack to allow adjusting bundle compression
1263 # level without a) formalizing the bundlespec changes to declare it
1263 # level without a) formalizing the bundlespec changes to declare it
1264 # b) introducing a command flag.
1264 # b) introducing a command flag.
1265 compopts = {}
1265 compopts = {}
1266 complevel = ui.configint('experimental', 'bundlecomplevel')
1266 complevel = ui.configint('experimental', 'bundlecomplevel')
1267 if complevel is not None:
1267 if complevel is not None:
1268 compopts['level'] = complevel
1268 compopts['level'] = complevel
1269
1269
1270 # Allow overriding the bundling of obsmarker in phases through
1270 # Allow overriding the bundling of obsmarker in phases through
1271 # configuration while we don't have a bundle version that include them
1271 # configuration while we don't have a bundle version that include them
1272 if repo.ui.configbool('experimental', 'evolution.bundle-obsmarker'):
1272 if repo.ui.configbool('experimental', 'evolution.bundle-obsmarker'):
1273 bundlespec.contentopts['obsolescence'] = True
1273 bundlespec.contentopts['obsolescence'] = True
1274 if repo.ui.configbool('experimental', 'bundle-phases'):
1274 if repo.ui.configbool('experimental', 'bundle-phases'):
1275 bundlespec.contentopts['phases'] = True
1275 bundlespec.contentopts['phases'] = True
1276
1276
1277 bundle2.writenewbundle(ui, repo, 'bundle', fname, bversion, outgoing,
1277 bundle2.writenewbundle(ui, repo, 'bundle', fname, bversion, outgoing,
1278 bundlespec.contentopts, compression=bcompression,
1278 bundlespec.contentopts, compression=bcompression,
1279 compopts=compopts)
1279 compopts=compopts)
1280
1280
1281 @command('cat',
1281 @command('cat',
1282 [('o', 'output', '',
1282 [('o', 'output', '',
1283 _('print output to file with formatted name'), _('FORMAT')),
1283 _('print output to file with formatted name'), _('FORMAT')),
1284 ('r', 'rev', '', _('print the given revision'), _('REV')),
1284 ('r', 'rev', '', _('print the given revision'), _('REV')),
1285 ('', 'decode', None, _('apply any matching decode filter')),
1285 ('', 'decode', None, _('apply any matching decode filter')),
1286 ] + walkopts + formatteropts,
1286 ] + walkopts + formatteropts,
1287 _('[OPTION]... FILE...'),
1287 _('[OPTION]... FILE...'),
1288 inferrepo=True, cmdtype=readonly)
1288 inferrepo=True, cmdtype=readonly)
1289 def cat(ui, repo, file1, *pats, **opts):
1289 def cat(ui, repo, file1, *pats, **opts):
1290 """output the current or given revision of files
1290 """output the current or given revision of files
1291
1291
1292 Print the specified files as they were at the given revision. If
1292 Print the specified files as they were at the given revision. If
1293 no revision is given, the parent of the working directory is used.
1293 no revision is given, the parent of the working directory is used.
1294
1294
1295 Output may be to a file, in which case the name of the file is
1295 Output may be to a file, in which case the name of the file is
1296 given using a template string. See :hg:`help templates`. In addition
1296 given using a template string. See :hg:`help templates`. In addition
1297 to the common template keywords, the following formatting rules are
1297 to the common template keywords, the following formatting rules are
1298 supported:
1298 supported:
1299
1299
1300 :``%%``: literal "%" character
1300 :``%%``: literal "%" character
1301 :``%s``: basename of file being printed
1301 :``%s``: basename of file being printed
1302 :``%d``: dirname of file being printed, or '.' if in repository root
1302 :``%d``: dirname of file being printed, or '.' if in repository root
1303 :``%p``: root-relative path name of file being printed
1303 :``%p``: root-relative path name of file being printed
1304 :``%H``: changeset hash (40 hexadecimal digits)
1304 :``%H``: changeset hash (40 hexadecimal digits)
1305 :``%R``: changeset revision number
1305 :``%R``: changeset revision number
1306 :``%h``: short-form changeset hash (12 hexadecimal digits)
1306 :``%h``: short-form changeset hash (12 hexadecimal digits)
1307 :``%r``: zero-padded changeset revision number
1307 :``%r``: zero-padded changeset revision number
1308 :``%b``: basename of the exporting repository
1308 :``%b``: basename of the exporting repository
1309 :``\\``: literal "\\" character
1309 :``\\``: literal "\\" character
1310
1310
1311 Returns 0 on success.
1311 Returns 0 on success.
1312 """
1312 """
1313 opts = pycompat.byteskwargs(opts)
1313 opts = pycompat.byteskwargs(opts)
1314 rev = opts.get('rev')
1314 rev = opts.get('rev')
1315 if rev:
1315 if rev:
1316 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
1316 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
1317 ctx = scmutil.revsingle(repo, rev)
1317 ctx = scmutil.revsingle(repo, rev)
1318 m = scmutil.match(ctx, (file1,) + pats, opts)
1318 m = scmutil.match(ctx, (file1,) + pats, opts)
1319 fntemplate = opts.pop('output', '')
1319 fntemplate = opts.pop('output', '')
1320 if cmdutil.isstdiofilename(fntemplate):
1320 if cmdutil.isstdiofilename(fntemplate):
1321 fntemplate = ''
1321 fntemplate = ''
1322
1322
1323 if fntemplate:
1323 if fntemplate:
1324 fm = formatter.nullformatter(ui, 'cat')
1324 fm = formatter.nullformatter(ui, 'cat')
1325 else:
1325 else:
1326 ui.pager('cat')
1326 ui.pager('cat')
1327 fm = ui.formatter('cat', opts)
1327 fm = ui.formatter('cat', opts)
1328 with fm:
1328 with fm:
1329 return cmdutil.cat(ui, repo, ctx, m, fm, fntemplate, '',
1329 return cmdutil.cat(ui, repo, ctx, m, fm, fntemplate, '',
1330 **pycompat.strkwargs(opts))
1330 **pycompat.strkwargs(opts))
1331
1331
1332 @command('^clone',
1332 @command('^clone',
1333 [('U', 'noupdate', None, _('the clone will include an empty working '
1333 [('U', 'noupdate', None, _('the clone will include an empty working '
1334 'directory (only a repository)')),
1334 'directory (only a repository)')),
1335 ('u', 'updaterev', '', _('revision, tag, or branch to check out'),
1335 ('u', 'updaterev', '', _('revision, tag, or branch to check out'),
1336 _('REV')),
1336 _('REV')),
1337 ('r', 'rev', [], _('do not clone everything, but include this changeset'
1337 ('r', 'rev', [], _('do not clone everything, but include this changeset'
1338 ' and its ancestors'), _('REV')),
1338 ' and its ancestors'), _('REV')),
1339 ('b', 'branch', [], _('do not clone everything, but include this branch\'s'
1339 ('b', 'branch', [], _('do not clone everything, but include this branch\'s'
1340 ' changesets and their ancestors'), _('BRANCH')),
1340 ' changesets and their ancestors'), _('BRANCH')),
1341 ('', 'pull', None, _('use pull protocol to copy metadata')),
1341 ('', 'pull', None, _('use pull protocol to copy metadata')),
1342 ('', 'uncompressed', None,
1342 ('', 'uncompressed', None,
1343 _('an alias to --stream (DEPRECATED)')),
1343 _('an alias to --stream (DEPRECATED)')),
1344 ('', 'stream', None,
1344 ('', 'stream', None,
1345 _('clone with minimal data processing')),
1345 _('clone with minimal data processing')),
1346 ] + remoteopts,
1346 ] + remoteopts,
1347 _('[OPTION]... SOURCE [DEST]'),
1347 _('[OPTION]... SOURCE [DEST]'),
1348 norepo=True)
1348 norepo=True)
1349 def clone(ui, source, dest=None, **opts):
1349 def clone(ui, source, dest=None, **opts):
1350 """make a copy of an existing repository
1350 """make a copy of an existing repository
1351
1351
1352 Create a copy of an existing repository in a new directory.
1352 Create a copy of an existing repository in a new directory.
1353
1353
1354 If no destination directory name is specified, it defaults to the
1354 If no destination directory name is specified, it defaults to the
1355 basename of the source.
1355 basename of the source.
1356
1356
1357 The location of the source is added to the new repository's
1357 The location of the source is added to the new repository's
1358 ``.hg/hgrc`` file, as the default to be used for future pulls.
1358 ``.hg/hgrc`` file, as the default to be used for future pulls.
1359
1359
1360 Only local paths and ``ssh://`` URLs are supported as
1360 Only local paths and ``ssh://`` URLs are supported as
1361 destinations. For ``ssh://`` destinations, no working directory or
1361 destinations. For ``ssh://`` destinations, no working directory or
1362 ``.hg/hgrc`` will be created on the remote side.
1362 ``.hg/hgrc`` will be created on the remote side.
1363
1363
1364 If the source repository has a bookmark called '@' set, that
1364 If the source repository has a bookmark called '@' set, that
1365 revision will be checked out in the new repository by default.
1365 revision will be checked out in the new repository by default.
1366
1366
1367 To check out a particular version, use -u/--update, or
1367 To check out a particular version, use -u/--update, or
1368 -U/--noupdate to create a clone with no working directory.
1368 -U/--noupdate to create a clone with no working directory.
1369
1369
1370 To pull only a subset of changesets, specify one or more revisions
1370 To pull only a subset of changesets, specify one or more revisions
1371 identifiers with -r/--rev or branches with -b/--branch. The
1371 identifiers with -r/--rev or branches with -b/--branch. The
1372 resulting clone will contain only the specified changesets and
1372 resulting clone will contain only the specified changesets and
1373 their ancestors. These options (or 'clone src#rev dest') imply
1373 their ancestors. These options (or 'clone src#rev dest') imply
1374 --pull, even for local source repositories.
1374 --pull, even for local source repositories.
1375
1375
1376 In normal clone mode, the remote normalizes repository data into a common
1376 In normal clone mode, the remote normalizes repository data into a common
1377 exchange format and the receiving end translates this data into its local
1377 exchange format and the receiving end translates this data into its local
1378 storage format. --stream activates a different clone mode that essentially
1378 storage format. --stream activates a different clone mode that essentially
1379 copies repository files from the remote with minimal data processing. This
1379 copies repository files from the remote with minimal data processing. This
1380 significantly reduces the CPU cost of a clone both remotely and locally.
1380 significantly reduces the CPU cost of a clone both remotely and locally.
1381 However, it often increases the transferred data size by 30-40%. This can
1381 However, it often increases the transferred data size by 30-40%. This can
1382 result in substantially faster clones where I/O throughput is plentiful,
1382 result in substantially faster clones where I/O throughput is plentiful,
1383 especially for larger repositories. A side-effect of --stream clones is
1383 especially for larger repositories. A side-effect of --stream clones is
1384 that storage settings and requirements on the remote are applied locally:
1384 that storage settings and requirements on the remote are applied locally:
1385 a modern client may inherit legacy or inefficient storage used by the
1385 a modern client may inherit legacy or inefficient storage used by the
1386 remote or a legacy Mercurial client may not be able to clone from a
1386 remote or a legacy Mercurial client may not be able to clone from a
1387 modern Mercurial remote.
1387 modern Mercurial remote.
1388
1388
1389 .. note::
1389 .. note::
1390
1390
1391 Specifying a tag will include the tagged changeset but not the
1391 Specifying a tag will include the tagged changeset but not the
1392 changeset containing the tag.
1392 changeset containing the tag.
1393
1393
1394 .. container:: verbose
1394 .. container:: verbose
1395
1395
1396 For efficiency, hardlinks are used for cloning whenever the
1396 For efficiency, hardlinks are used for cloning whenever the
1397 source and destination are on the same filesystem (note this
1397 source and destination are on the same filesystem (note this
1398 applies only to the repository data, not to the working
1398 applies only to the repository data, not to the working
1399 directory). Some filesystems, such as AFS, implement hardlinking
1399 directory). Some filesystems, such as AFS, implement hardlinking
1400 incorrectly, but do not report errors. In these cases, use the
1400 incorrectly, but do not report errors. In these cases, use the
1401 --pull option to avoid hardlinking.
1401 --pull option to avoid hardlinking.
1402
1402
1403 Mercurial will update the working directory to the first applicable
1403 Mercurial will update the working directory to the first applicable
1404 revision from this list:
1404 revision from this list:
1405
1405
1406 a) null if -U or the source repository has no changesets
1406 a) null if -U or the source repository has no changesets
1407 b) if -u . and the source repository is local, the first parent of
1407 b) if -u . and the source repository is local, the first parent of
1408 the source repository's working directory
1408 the source repository's working directory
1409 c) the changeset specified with -u (if a branch name, this means the
1409 c) the changeset specified with -u (if a branch name, this means the
1410 latest head of that branch)
1410 latest head of that branch)
1411 d) the changeset specified with -r
1411 d) the changeset specified with -r
1412 e) the tipmost head specified with -b
1412 e) the tipmost head specified with -b
1413 f) the tipmost head specified with the url#branch source syntax
1413 f) the tipmost head specified with the url#branch source syntax
1414 g) the revision marked with the '@' bookmark, if present
1414 g) the revision marked with the '@' bookmark, if present
1415 h) the tipmost head of the default branch
1415 h) the tipmost head of the default branch
1416 i) tip
1416 i) tip
1417
1417
1418 When cloning from servers that support it, Mercurial may fetch
1418 When cloning from servers that support it, Mercurial may fetch
1419 pre-generated data from a server-advertised URL. When this is done,
1419 pre-generated data from a server-advertised URL. When this is done,
1420 hooks operating on incoming changesets and changegroups may fire twice,
1420 hooks operating on incoming changesets and changegroups may fire twice,
1421 once for the bundle fetched from the URL and another for any additional
1421 once for the bundle fetched from the URL and another for any additional
1422 data not fetched from this URL. In addition, if an error occurs, the
1422 data not fetched from this URL. In addition, if an error occurs, the
1423 repository may be rolled back to a partial clone. This behavior may
1423 repository may be rolled back to a partial clone. This behavior may
1424 change in future releases. See :hg:`help -e clonebundles` for more.
1424 change in future releases. See :hg:`help -e clonebundles` for more.
1425
1425
1426 Examples:
1426 Examples:
1427
1427
1428 - clone a remote repository to a new directory named hg/::
1428 - clone a remote repository to a new directory named hg/::
1429
1429
1430 hg clone https://www.mercurial-scm.org/repo/hg/
1430 hg clone https://www.mercurial-scm.org/repo/hg/
1431
1431
1432 - create a lightweight local clone::
1432 - create a lightweight local clone::
1433
1433
1434 hg clone project/ project-feature/
1434 hg clone project/ project-feature/
1435
1435
1436 - clone from an absolute path on an ssh server (note double-slash)::
1436 - clone from an absolute path on an ssh server (note double-slash)::
1437
1437
1438 hg clone ssh://user@server//home/projects/alpha/
1438 hg clone ssh://user@server//home/projects/alpha/
1439
1439
1440 - do a streaming clone while checking out a specified version::
1440 - do a streaming clone while checking out a specified version::
1441
1441
1442 hg clone --stream http://server/repo -u 1.5
1442 hg clone --stream http://server/repo -u 1.5
1443
1443
1444 - create a repository without changesets after a particular revision::
1444 - create a repository without changesets after a particular revision::
1445
1445
1446 hg clone -r 04e544 experimental/ good/
1446 hg clone -r 04e544 experimental/ good/
1447
1447
1448 - clone (and track) a particular named branch::
1448 - clone (and track) a particular named branch::
1449
1449
1450 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1450 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1451
1451
1452 See :hg:`help urls` for details on specifying URLs.
1452 See :hg:`help urls` for details on specifying URLs.
1453
1453
1454 Returns 0 on success.
1454 Returns 0 on success.
1455 """
1455 """
1456 opts = pycompat.byteskwargs(opts)
1456 opts = pycompat.byteskwargs(opts)
1457 if opts.get('noupdate') and opts.get('updaterev'):
1457 if opts.get('noupdate') and opts.get('updaterev'):
1458 raise error.Abort(_("cannot specify both --noupdate and --updaterev"))
1458 raise error.Abort(_("cannot specify both --noupdate and --updaterev"))
1459
1459
1460 r = hg.clone(ui, opts, source, dest,
1460 r = hg.clone(ui, opts, source, dest,
1461 pull=opts.get('pull'),
1461 pull=opts.get('pull'),
1462 stream=opts.get('stream') or opts.get('uncompressed'),
1462 stream=opts.get('stream') or opts.get('uncompressed'),
1463 rev=opts.get('rev'),
1463 revs=opts.get('rev'),
1464 update=opts.get('updaterev') or not opts.get('noupdate'),
1464 update=opts.get('updaterev') or not opts.get('noupdate'),
1465 branch=opts.get('branch'),
1465 branch=opts.get('branch'),
1466 shareopts=opts.get('shareopts'))
1466 shareopts=opts.get('shareopts'))
1467
1467
1468 return r is None
1468 return r is None
1469
1469
1470 @command('^commit|ci',
1470 @command('^commit|ci',
1471 [('A', 'addremove', None,
1471 [('A', 'addremove', None,
1472 _('mark new/missing files as added/removed before committing')),
1472 _('mark new/missing files as added/removed before committing')),
1473 ('', 'close-branch', None,
1473 ('', 'close-branch', None,
1474 _('mark a branch head as closed')),
1474 _('mark a branch head as closed')),
1475 ('', 'amend', None, _('amend the parent of the working directory')),
1475 ('', 'amend', None, _('amend the parent of the working directory')),
1476 ('s', 'secret', None, _('use the secret phase for committing')),
1476 ('s', 'secret', None, _('use the secret phase for committing')),
1477 ('e', 'edit', None, _('invoke editor on commit messages')),
1477 ('e', 'edit', None, _('invoke editor on commit messages')),
1478 ('i', 'interactive', None, _('use interactive mode')),
1478 ('i', 'interactive', None, _('use interactive mode')),
1479 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1479 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1480 _('[OPTION]... [FILE]...'),
1480 _('[OPTION]... [FILE]...'),
1481 inferrepo=True)
1481 inferrepo=True)
1482 def commit(ui, repo, *pats, **opts):
1482 def commit(ui, repo, *pats, **opts):
1483 """commit the specified files or all outstanding changes
1483 """commit the specified files or all outstanding changes
1484
1484
1485 Commit changes to the given files into the repository. Unlike a
1485 Commit changes to the given files into the repository. Unlike a
1486 centralized SCM, this operation is a local operation. See
1486 centralized SCM, this operation is a local operation. See
1487 :hg:`push` for a way to actively distribute your changes.
1487 :hg:`push` for a way to actively distribute your changes.
1488
1488
1489 If a list of files is omitted, all changes reported by :hg:`status`
1489 If a list of files is omitted, all changes reported by :hg:`status`
1490 will be committed.
1490 will be committed.
1491
1491
1492 If you are committing the result of a merge, do not provide any
1492 If you are committing the result of a merge, do not provide any
1493 filenames or -I/-X filters.
1493 filenames or -I/-X filters.
1494
1494
1495 If no commit message is specified, Mercurial starts your
1495 If no commit message is specified, Mercurial starts your
1496 configured editor where you can enter a message. In case your
1496 configured editor where you can enter a message. In case your
1497 commit fails, you will find a backup of your message in
1497 commit fails, you will find a backup of your message in
1498 ``.hg/last-message.txt``.
1498 ``.hg/last-message.txt``.
1499
1499
1500 The --close-branch flag can be used to mark the current branch
1500 The --close-branch flag can be used to mark the current branch
1501 head closed. When all heads of a branch are closed, the branch
1501 head closed. When all heads of a branch are closed, the branch
1502 will be considered closed and no longer listed.
1502 will be considered closed and no longer listed.
1503
1503
1504 The --amend flag can be used to amend the parent of the
1504 The --amend flag can be used to amend the parent of the
1505 working directory with a new commit that contains the changes
1505 working directory with a new commit that contains the changes
1506 in the parent in addition to those currently reported by :hg:`status`,
1506 in the parent in addition to those currently reported by :hg:`status`,
1507 if there are any. The old commit is stored in a backup bundle in
1507 if there are any. The old commit is stored in a backup bundle in
1508 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1508 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1509 on how to restore it).
1509 on how to restore it).
1510
1510
1511 Message, user and date are taken from the amended commit unless
1511 Message, user and date are taken from the amended commit unless
1512 specified. When a message isn't specified on the command line,
1512 specified. When a message isn't specified on the command line,
1513 the editor will open with the message of the amended commit.
1513 the editor will open with the message of the amended commit.
1514
1514
1515 It is not possible to amend public changesets (see :hg:`help phases`)
1515 It is not possible to amend public changesets (see :hg:`help phases`)
1516 or changesets that have children.
1516 or changesets that have children.
1517
1517
1518 See :hg:`help dates` for a list of formats valid for -d/--date.
1518 See :hg:`help dates` for a list of formats valid for -d/--date.
1519
1519
1520 Returns 0 on success, 1 if nothing changed.
1520 Returns 0 on success, 1 if nothing changed.
1521
1521
1522 .. container:: verbose
1522 .. container:: verbose
1523
1523
1524 Examples:
1524 Examples:
1525
1525
1526 - commit all files ending in .py::
1526 - commit all files ending in .py::
1527
1527
1528 hg commit --include "set:**.py"
1528 hg commit --include "set:**.py"
1529
1529
1530 - commit all non-binary files::
1530 - commit all non-binary files::
1531
1531
1532 hg commit --exclude "set:binary()"
1532 hg commit --exclude "set:binary()"
1533
1533
1534 - amend the current commit and set the date to now::
1534 - amend the current commit and set the date to now::
1535
1535
1536 hg commit --amend --date now
1536 hg commit --amend --date now
1537 """
1537 """
1538 wlock = lock = None
1538 wlock = lock = None
1539 try:
1539 try:
1540 wlock = repo.wlock()
1540 wlock = repo.wlock()
1541 lock = repo.lock()
1541 lock = repo.lock()
1542 return _docommit(ui, repo, *pats, **opts)
1542 return _docommit(ui, repo, *pats, **opts)
1543 finally:
1543 finally:
1544 release(lock, wlock)
1544 release(lock, wlock)
1545
1545
1546 def _docommit(ui, repo, *pats, **opts):
1546 def _docommit(ui, repo, *pats, **opts):
1547 if opts.get(r'interactive'):
1547 if opts.get(r'interactive'):
1548 opts.pop(r'interactive')
1548 opts.pop(r'interactive')
1549 ret = cmdutil.dorecord(ui, repo, commit, None, False,
1549 ret = cmdutil.dorecord(ui, repo, commit, None, False,
1550 cmdutil.recordfilter, *pats,
1550 cmdutil.recordfilter, *pats,
1551 **opts)
1551 **opts)
1552 # ret can be 0 (no changes to record) or the value returned by
1552 # ret can be 0 (no changes to record) or the value returned by
1553 # commit(), 1 if nothing changed or None on success.
1553 # commit(), 1 if nothing changed or None on success.
1554 return 1 if ret == 0 else ret
1554 return 1 if ret == 0 else ret
1555
1555
1556 opts = pycompat.byteskwargs(opts)
1556 opts = pycompat.byteskwargs(opts)
1557 if opts.get('subrepos'):
1557 if opts.get('subrepos'):
1558 if opts.get('amend'):
1558 if opts.get('amend'):
1559 raise error.Abort(_('cannot amend with --subrepos'))
1559 raise error.Abort(_('cannot amend with --subrepos'))
1560 # Let --subrepos on the command line override config setting.
1560 # Let --subrepos on the command line override config setting.
1561 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1561 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1562
1562
1563 cmdutil.checkunfinished(repo, commit=True)
1563 cmdutil.checkunfinished(repo, commit=True)
1564
1564
1565 branch = repo[None].branch()
1565 branch = repo[None].branch()
1566 bheads = repo.branchheads(branch)
1566 bheads = repo.branchheads(branch)
1567
1567
1568 extra = {}
1568 extra = {}
1569 if opts.get('close_branch'):
1569 if opts.get('close_branch'):
1570 extra['close'] = '1'
1570 extra['close'] = '1'
1571
1571
1572 if not bheads:
1572 if not bheads:
1573 raise error.Abort(_('can only close branch heads'))
1573 raise error.Abort(_('can only close branch heads'))
1574 elif opts.get('amend'):
1574 elif opts.get('amend'):
1575 if repo[None].parents()[0].p1().branch() != branch and \
1575 if repo[None].parents()[0].p1().branch() != branch and \
1576 repo[None].parents()[0].p2().branch() != branch:
1576 repo[None].parents()[0].p2().branch() != branch:
1577 raise error.Abort(_('can only close branch heads'))
1577 raise error.Abort(_('can only close branch heads'))
1578
1578
1579 if opts.get('amend'):
1579 if opts.get('amend'):
1580 if ui.configbool('ui', 'commitsubrepos'):
1580 if ui.configbool('ui', 'commitsubrepos'):
1581 raise error.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1581 raise error.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1582
1582
1583 old = repo['.']
1583 old = repo['.']
1584 rewriteutil.precheck(repo, [old.rev()], 'amend')
1584 rewriteutil.precheck(repo, [old.rev()], 'amend')
1585
1585
1586 # Currently histedit gets confused if an amend happens while histedit
1586 # Currently histedit gets confused if an amend happens while histedit
1587 # is in progress. Since we have a checkunfinished command, we are
1587 # is in progress. Since we have a checkunfinished command, we are
1588 # temporarily honoring it.
1588 # temporarily honoring it.
1589 #
1589 #
1590 # Note: eventually this guard will be removed. Please do not expect
1590 # Note: eventually this guard will be removed. Please do not expect
1591 # this behavior to remain.
1591 # this behavior to remain.
1592 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
1592 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
1593 cmdutil.checkunfinished(repo)
1593 cmdutil.checkunfinished(repo)
1594
1594
1595 node = cmdutil.amend(ui, repo, old, extra, pats, opts)
1595 node = cmdutil.amend(ui, repo, old, extra, pats, opts)
1596 if node == old.node():
1596 if node == old.node():
1597 ui.status(_("nothing changed\n"))
1597 ui.status(_("nothing changed\n"))
1598 return 1
1598 return 1
1599 else:
1599 else:
1600 def commitfunc(ui, repo, message, match, opts):
1600 def commitfunc(ui, repo, message, match, opts):
1601 overrides = {}
1601 overrides = {}
1602 if opts.get('secret'):
1602 if opts.get('secret'):
1603 overrides[('phases', 'new-commit')] = 'secret'
1603 overrides[('phases', 'new-commit')] = 'secret'
1604
1604
1605 baseui = repo.baseui
1605 baseui = repo.baseui
1606 with baseui.configoverride(overrides, 'commit'):
1606 with baseui.configoverride(overrides, 'commit'):
1607 with ui.configoverride(overrides, 'commit'):
1607 with ui.configoverride(overrides, 'commit'):
1608 editform = cmdutil.mergeeditform(repo[None],
1608 editform = cmdutil.mergeeditform(repo[None],
1609 'commit.normal')
1609 'commit.normal')
1610 editor = cmdutil.getcommiteditor(
1610 editor = cmdutil.getcommiteditor(
1611 editform=editform, **pycompat.strkwargs(opts))
1611 editform=editform, **pycompat.strkwargs(opts))
1612 return repo.commit(message,
1612 return repo.commit(message,
1613 opts.get('user'),
1613 opts.get('user'),
1614 opts.get('date'),
1614 opts.get('date'),
1615 match,
1615 match,
1616 editor=editor,
1616 editor=editor,
1617 extra=extra)
1617 extra=extra)
1618
1618
1619 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1619 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1620
1620
1621 if not node:
1621 if not node:
1622 stat = cmdutil.postcommitstatus(repo, pats, opts)
1622 stat = cmdutil.postcommitstatus(repo, pats, opts)
1623 if stat[3]:
1623 if stat[3]:
1624 ui.status(_("nothing changed (%d missing files, see "
1624 ui.status(_("nothing changed (%d missing files, see "
1625 "'hg status')\n") % len(stat[3]))
1625 "'hg status')\n") % len(stat[3]))
1626 else:
1626 else:
1627 ui.status(_("nothing changed\n"))
1627 ui.status(_("nothing changed\n"))
1628 return 1
1628 return 1
1629
1629
1630 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1630 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1631
1631
1632 @command('config|showconfig|debugconfig',
1632 @command('config|showconfig|debugconfig',
1633 [('u', 'untrusted', None, _('show untrusted configuration options')),
1633 [('u', 'untrusted', None, _('show untrusted configuration options')),
1634 ('e', 'edit', None, _('edit user config')),
1634 ('e', 'edit', None, _('edit user config')),
1635 ('l', 'local', None, _('edit repository config')),
1635 ('l', 'local', None, _('edit repository config')),
1636 ('g', 'global', None, _('edit global config'))] + formatteropts,
1636 ('g', 'global', None, _('edit global config'))] + formatteropts,
1637 _('[-u] [NAME]...'),
1637 _('[-u] [NAME]...'),
1638 optionalrepo=True, cmdtype=readonly)
1638 optionalrepo=True, cmdtype=readonly)
1639 def config(ui, repo, *values, **opts):
1639 def config(ui, repo, *values, **opts):
1640 """show combined config settings from all hgrc files
1640 """show combined config settings from all hgrc files
1641
1641
1642 With no arguments, print names and values of all config items.
1642 With no arguments, print names and values of all config items.
1643
1643
1644 With one argument of the form section.name, print just the value
1644 With one argument of the form section.name, print just the value
1645 of that config item.
1645 of that config item.
1646
1646
1647 With multiple arguments, print names and values of all config
1647 With multiple arguments, print names and values of all config
1648 items with matching section names or section.names.
1648 items with matching section names or section.names.
1649
1649
1650 With --edit, start an editor on the user-level config file. With
1650 With --edit, start an editor on the user-level config file. With
1651 --global, edit the system-wide config file. With --local, edit the
1651 --global, edit the system-wide config file. With --local, edit the
1652 repository-level config file.
1652 repository-level config file.
1653
1653
1654 With --debug, the source (filename and line number) is printed
1654 With --debug, the source (filename and line number) is printed
1655 for each config item.
1655 for each config item.
1656
1656
1657 See :hg:`help config` for more information about config files.
1657 See :hg:`help config` for more information about config files.
1658
1658
1659 Returns 0 on success, 1 if NAME does not exist.
1659 Returns 0 on success, 1 if NAME does not exist.
1660
1660
1661 """
1661 """
1662
1662
1663 opts = pycompat.byteskwargs(opts)
1663 opts = pycompat.byteskwargs(opts)
1664 if opts.get('edit') or opts.get('local') or opts.get('global'):
1664 if opts.get('edit') or opts.get('local') or opts.get('global'):
1665 if opts.get('local') and opts.get('global'):
1665 if opts.get('local') and opts.get('global'):
1666 raise error.Abort(_("can't use --local and --global together"))
1666 raise error.Abort(_("can't use --local and --global together"))
1667
1667
1668 if opts.get('local'):
1668 if opts.get('local'):
1669 if not repo:
1669 if not repo:
1670 raise error.Abort(_("can't use --local outside a repository"))
1670 raise error.Abort(_("can't use --local outside a repository"))
1671 paths = [repo.vfs.join('hgrc')]
1671 paths = [repo.vfs.join('hgrc')]
1672 elif opts.get('global'):
1672 elif opts.get('global'):
1673 paths = rcutil.systemrcpath()
1673 paths = rcutil.systemrcpath()
1674 else:
1674 else:
1675 paths = rcutil.userrcpath()
1675 paths = rcutil.userrcpath()
1676
1676
1677 for f in paths:
1677 for f in paths:
1678 if os.path.exists(f):
1678 if os.path.exists(f):
1679 break
1679 break
1680 else:
1680 else:
1681 if opts.get('global'):
1681 if opts.get('global'):
1682 samplehgrc = uimod.samplehgrcs['global']
1682 samplehgrc = uimod.samplehgrcs['global']
1683 elif opts.get('local'):
1683 elif opts.get('local'):
1684 samplehgrc = uimod.samplehgrcs['local']
1684 samplehgrc = uimod.samplehgrcs['local']
1685 else:
1685 else:
1686 samplehgrc = uimod.samplehgrcs['user']
1686 samplehgrc = uimod.samplehgrcs['user']
1687
1687
1688 f = paths[0]
1688 f = paths[0]
1689 fp = open(f, "wb")
1689 fp = open(f, "wb")
1690 fp.write(util.tonativeeol(samplehgrc))
1690 fp.write(util.tonativeeol(samplehgrc))
1691 fp.close()
1691 fp.close()
1692
1692
1693 editor = ui.geteditor()
1693 editor = ui.geteditor()
1694 ui.system("%s \"%s\"" % (editor, f),
1694 ui.system("%s \"%s\"" % (editor, f),
1695 onerr=error.Abort, errprefix=_("edit failed"),
1695 onerr=error.Abort, errprefix=_("edit failed"),
1696 blockedtag='config_edit')
1696 blockedtag='config_edit')
1697 return
1697 return
1698 ui.pager('config')
1698 ui.pager('config')
1699 fm = ui.formatter('config', opts)
1699 fm = ui.formatter('config', opts)
1700 for t, f in rcutil.rccomponents():
1700 for t, f in rcutil.rccomponents():
1701 if t == 'path':
1701 if t == 'path':
1702 ui.debug('read config from: %s\n' % f)
1702 ui.debug('read config from: %s\n' % f)
1703 elif t == 'items':
1703 elif t == 'items':
1704 for section, name, value, source in f:
1704 for section, name, value, source in f:
1705 ui.debug('set config by: %s\n' % source)
1705 ui.debug('set config by: %s\n' % source)
1706 else:
1706 else:
1707 raise error.ProgrammingError('unknown rctype: %s' % t)
1707 raise error.ProgrammingError('unknown rctype: %s' % t)
1708 untrusted = bool(opts.get('untrusted'))
1708 untrusted = bool(opts.get('untrusted'))
1709
1709
1710 selsections = selentries = []
1710 selsections = selentries = []
1711 if values:
1711 if values:
1712 selsections = [v for v in values if '.' not in v]
1712 selsections = [v for v in values if '.' not in v]
1713 selentries = [v for v in values if '.' in v]
1713 selentries = [v for v in values if '.' in v]
1714 uniquesel = (len(selentries) == 1 and not selsections)
1714 uniquesel = (len(selentries) == 1 and not selsections)
1715 selsections = set(selsections)
1715 selsections = set(selsections)
1716 selentries = set(selentries)
1716 selentries = set(selentries)
1717
1717
1718 matched = False
1718 matched = False
1719 for section, name, value in ui.walkconfig(untrusted=untrusted):
1719 for section, name, value in ui.walkconfig(untrusted=untrusted):
1720 source = ui.configsource(section, name, untrusted)
1720 source = ui.configsource(section, name, untrusted)
1721 value = pycompat.bytestr(value)
1721 value = pycompat.bytestr(value)
1722 if fm.isplain():
1722 if fm.isplain():
1723 source = source or 'none'
1723 source = source or 'none'
1724 value = value.replace('\n', '\\n')
1724 value = value.replace('\n', '\\n')
1725 entryname = section + '.' + name
1725 entryname = section + '.' + name
1726 if values and not (section in selsections or entryname in selentries):
1726 if values and not (section in selsections or entryname in selentries):
1727 continue
1727 continue
1728 fm.startitem()
1728 fm.startitem()
1729 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1729 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1730 if uniquesel:
1730 if uniquesel:
1731 fm.data(name=entryname)
1731 fm.data(name=entryname)
1732 fm.write('value', '%s\n', value)
1732 fm.write('value', '%s\n', value)
1733 else:
1733 else:
1734 fm.write('name value', '%s=%s\n', entryname, value)
1734 fm.write('name value', '%s=%s\n', entryname, value)
1735 matched = True
1735 matched = True
1736 fm.end()
1736 fm.end()
1737 if matched:
1737 if matched:
1738 return 0
1738 return 0
1739 return 1
1739 return 1
1740
1740
1741 @command('copy|cp',
1741 @command('copy|cp',
1742 [('A', 'after', None, _('record a copy that has already occurred')),
1742 [('A', 'after', None, _('record a copy that has already occurred')),
1743 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1743 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1744 ] + walkopts + dryrunopts,
1744 ] + walkopts + dryrunopts,
1745 _('[OPTION]... [SOURCE]... DEST'))
1745 _('[OPTION]... [SOURCE]... DEST'))
1746 def copy(ui, repo, *pats, **opts):
1746 def copy(ui, repo, *pats, **opts):
1747 """mark files as copied for the next commit
1747 """mark files as copied for the next commit
1748
1748
1749 Mark dest as having copies of source files. If dest is a
1749 Mark dest as having copies of source files. If dest is a
1750 directory, copies are put in that directory. If dest is a file,
1750 directory, copies are put in that directory. If dest is a file,
1751 the source must be a single file.
1751 the source must be a single file.
1752
1752
1753 By default, this command copies the contents of files as they
1753 By default, this command copies the contents of files as they
1754 exist in the working directory. If invoked with -A/--after, the
1754 exist in the working directory. If invoked with -A/--after, the
1755 operation is recorded, but no copying is performed.
1755 operation is recorded, but no copying is performed.
1756
1756
1757 This command takes effect with the next commit. To undo a copy
1757 This command takes effect with the next commit. To undo a copy
1758 before that, see :hg:`revert`.
1758 before that, see :hg:`revert`.
1759
1759
1760 Returns 0 on success, 1 if errors are encountered.
1760 Returns 0 on success, 1 if errors are encountered.
1761 """
1761 """
1762 opts = pycompat.byteskwargs(opts)
1762 opts = pycompat.byteskwargs(opts)
1763 with repo.wlock(False):
1763 with repo.wlock(False):
1764 return cmdutil.copy(ui, repo, pats, opts)
1764 return cmdutil.copy(ui, repo, pats, opts)
1765
1765
1766 @command('debugcommands', [], _('[COMMAND]'), norepo=True)
1766 @command('debugcommands', [], _('[COMMAND]'), norepo=True)
1767 def debugcommands(ui, cmd='', *args):
1767 def debugcommands(ui, cmd='', *args):
1768 """list all available commands and options"""
1768 """list all available commands and options"""
1769 for cmd, vals in sorted(table.iteritems()):
1769 for cmd, vals in sorted(table.iteritems()):
1770 cmd = cmd.split('|')[0].strip('^')
1770 cmd = cmd.split('|')[0].strip('^')
1771 opts = ', '.join([i[1] for i in vals[1]])
1771 opts = ', '.join([i[1] for i in vals[1]])
1772 ui.write('%s: %s\n' % (cmd, opts))
1772 ui.write('%s: %s\n' % (cmd, opts))
1773
1773
1774 @command('debugcomplete',
1774 @command('debugcomplete',
1775 [('o', 'options', None, _('show the command options'))],
1775 [('o', 'options', None, _('show the command options'))],
1776 _('[-o] CMD'),
1776 _('[-o] CMD'),
1777 norepo=True)
1777 norepo=True)
1778 def debugcomplete(ui, cmd='', **opts):
1778 def debugcomplete(ui, cmd='', **opts):
1779 """returns the completion list associated with the given command"""
1779 """returns the completion list associated with the given command"""
1780
1780
1781 if opts.get(r'options'):
1781 if opts.get(r'options'):
1782 options = []
1782 options = []
1783 otables = [globalopts]
1783 otables = [globalopts]
1784 if cmd:
1784 if cmd:
1785 aliases, entry = cmdutil.findcmd(cmd, table, False)
1785 aliases, entry = cmdutil.findcmd(cmd, table, False)
1786 otables.append(entry[1])
1786 otables.append(entry[1])
1787 for t in otables:
1787 for t in otables:
1788 for o in t:
1788 for o in t:
1789 if "(DEPRECATED)" in o[3]:
1789 if "(DEPRECATED)" in o[3]:
1790 continue
1790 continue
1791 if o[0]:
1791 if o[0]:
1792 options.append('-%s' % o[0])
1792 options.append('-%s' % o[0])
1793 options.append('--%s' % o[1])
1793 options.append('--%s' % o[1])
1794 ui.write("%s\n" % "\n".join(options))
1794 ui.write("%s\n" % "\n".join(options))
1795 return
1795 return
1796
1796
1797 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
1797 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
1798 if ui.verbose:
1798 if ui.verbose:
1799 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1799 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1800 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1800 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1801
1801
1802 @command('^diff',
1802 @command('^diff',
1803 [('r', 'rev', [], _('revision'), _('REV')),
1803 [('r', 'rev', [], _('revision'), _('REV')),
1804 ('c', 'change', '', _('change made by revision'), _('REV'))
1804 ('c', 'change', '', _('change made by revision'), _('REV'))
1805 ] + diffopts + diffopts2 + walkopts + subrepoopts,
1805 ] + diffopts + diffopts2 + walkopts + subrepoopts,
1806 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
1806 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
1807 inferrepo=True, cmdtype=readonly)
1807 inferrepo=True, cmdtype=readonly)
1808 def diff(ui, repo, *pats, **opts):
1808 def diff(ui, repo, *pats, **opts):
1809 """diff repository (or selected files)
1809 """diff repository (or selected files)
1810
1810
1811 Show differences between revisions for the specified files.
1811 Show differences between revisions for the specified files.
1812
1812
1813 Differences between files are shown using the unified diff format.
1813 Differences between files are shown using the unified diff format.
1814
1814
1815 .. note::
1815 .. note::
1816
1816
1817 :hg:`diff` may generate unexpected results for merges, as it will
1817 :hg:`diff` may generate unexpected results for merges, as it will
1818 default to comparing against the working directory's first
1818 default to comparing against the working directory's first
1819 parent changeset if no revisions are specified.
1819 parent changeset if no revisions are specified.
1820
1820
1821 When two revision arguments are given, then changes are shown
1821 When two revision arguments are given, then changes are shown
1822 between those revisions. If only one revision is specified then
1822 between those revisions. If only one revision is specified then
1823 that revision is compared to the working directory, and, when no
1823 that revision is compared to the working directory, and, when no
1824 revisions are specified, the working directory files are compared
1824 revisions are specified, the working directory files are compared
1825 to its first parent.
1825 to its first parent.
1826
1826
1827 Alternatively you can specify -c/--change with a revision to see
1827 Alternatively you can specify -c/--change with a revision to see
1828 the changes in that changeset relative to its first parent.
1828 the changes in that changeset relative to its first parent.
1829
1829
1830 Without the -a/--text option, diff will avoid generating diffs of
1830 Without the -a/--text option, diff will avoid generating diffs of
1831 files it detects as binary. With -a, diff will generate a diff
1831 files it detects as binary. With -a, diff will generate a diff
1832 anyway, probably with undesirable results.
1832 anyway, probably with undesirable results.
1833
1833
1834 Use the -g/--git option to generate diffs in the git extended diff
1834 Use the -g/--git option to generate diffs in the git extended diff
1835 format. For more information, read :hg:`help diffs`.
1835 format. For more information, read :hg:`help diffs`.
1836
1836
1837 .. container:: verbose
1837 .. container:: verbose
1838
1838
1839 Examples:
1839 Examples:
1840
1840
1841 - compare a file in the current working directory to its parent::
1841 - compare a file in the current working directory to its parent::
1842
1842
1843 hg diff foo.c
1843 hg diff foo.c
1844
1844
1845 - compare two historical versions of a directory, with rename info::
1845 - compare two historical versions of a directory, with rename info::
1846
1846
1847 hg diff --git -r 1.0:1.2 lib/
1847 hg diff --git -r 1.0:1.2 lib/
1848
1848
1849 - get change stats relative to the last change on some date::
1849 - get change stats relative to the last change on some date::
1850
1850
1851 hg diff --stat -r "date('may 2')"
1851 hg diff --stat -r "date('may 2')"
1852
1852
1853 - diff all newly-added files that contain a keyword::
1853 - diff all newly-added files that contain a keyword::
1854
1854
1855 hg diff "set:added() and grep(GNU)"
1855 hg diff "set:added() and grep(GNU)"
1856
1856
1857 - compare a revision and its parents::
1857 - compare a revision and its parents::
1858
1858
1859 hg diff -c 9353 # compare against first parent
1859 hg diff -c 9353 # compare against first parent
1860 hg diff -r 9353^:9353 # same using revset syntax
1860 hg diff -r 9353^:9353 # same using revset syntax
1861 hg diff -r 9353^2:9353 # compare against the second parent
1861 hg diff -r 9353^2:9353 # compare against the second parent
1862
1862
1863 Returns 0 on success.
1863 Returns 0 on success.
1864 """
1864 """
1865
1865
1866 opts = pycompat.byteskwargs(opts)
1866 opts = pycompat.byteskwargs(opts)
1867 revs = opts.get('rev')
1867 revs = opts.get('rev')
1868 change = opts.get('change')
1868 change = opts.get('change')
1869 stat = opts.get('stat')
1869 stat = opts.get('stat')
1870 reverse = opts.get('reverse')
1870 reverse = opts.get('reverse')
1871
1871
1872 if revs and change:
1872 if revs and change:
1873 msg = _('cannot specify --rev and --change at the same time')
1873 msg = _('cannot specify --rev and --change at the same time')
1874 raise error.Abort(msg)
1874 raise error.Abort(msg)
1875 elif change:
1875 elif change:
1876 repo = scmutil.unhidehashlikerevs(repo, [change], 'nowarn')
1876 repo = scmutil.unhidehashlikerevs(repo, [change], 'nowarn')
1877 ctx2 = scmutil.revsingle(repo, change, None)
1877 ctx2 = scmutil.revsingle(repo, change, None)
1878 ctx1 = ctx2.p1()
1878 ctx1 = ctx2.p1()
1879 else:
1879 else:
1880 repo = scmutil.unhidehashlikerevs(repo, revs, 'nowarn')
1880 repo = scmutil.unhidehashlikerevs(repo, revs, 'nowarn')
1881 ctx1, ctx2 = scmutil.revpair(repo, revs)
1881 ctx1, ctx2 = scmutil.revpair(repo, revs)
1882 node1, node2 = ctx1.node(), ctx2.node()
1882 node1, node2 = ctx1.node(), ctx2.node()
1883
1883
1884 if reverse:
1884 if reverse:
1885 node1, node2 = node2, node1
1885 node1, node2 = node2, node1
1886
1886
1887 diffopts = patch.diffallopts(ui, opts)
1887 diffopts = patch.diffallopts(ui, opts)
1888 m = scmutil.match(ctx2, pats, opts)
1888 m = scmutil.match(ctx2, pats, opts)
1889 ui.pager('diff')
1889 ui.pager('diff')
1890 logcmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
1890 logcmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
1891 listsubrepos=opts.get('subrepos'),
1891 listsubrepos=opts.get('subrepos'),
1892 root=opts.get('root'))
1892 root=opts.get('root'))
1893
1893
1894 @command('^export',
1894 @command('^export',
1895 [('o', 'output', '',
1895 [('o', 'output', '',
1896 _('print output to file with formatted name'), _('FORMAT')),
1896 _('print output to file with formatted name'), _('FORMAT')),
1897 ('', 'switch-parent', None, _('diff against the second parent')),
1897 ('', 'switch-parent', None, _('diff against the second parent')),
1898 ('r', 'rev', [], _('revisions to export'), _('REV')),
1898 ('r', 'rev', [], _('revisions to export'), _('REV')),
1899 ] + diffopts,
1899 ] + diffopts,
1900 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'), cmdtype=readonly)
1900 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'), cmdtype=readonly)
1901 def export(ui, repo, *changesets, **opts):
1901 def export(ui, repo, *changesets, **opts):
1902 """dump the header and diffs for one or more changesets
1902 """dump the header and diffs for one or more changesets
1903
1903
1904 Print the changeset header and diffs for one or more revisions.
1904 Print the changeset header and diffs for one or more revisions.
1905 If no revision is given, the parent of the working directory is used.
1905 If no revision is given, the parent of the working directory is used.
1906
1906
1907 The information shown in the changeset header is: author, date,
1907 The information shown in the changeset header is: author, date,
1908 branch name (if non-default), changeset hash, parent(s) and commit
1908 branch name (if non-default), changeset hash, parent(s) and commit
1909 comment.
1909 comment.
1910
1910
1911 .. note::
1911 .. note::
1912
1912
1913 :hg:`export` may generate unexpected diff output for merge
1913 :hg:`export` may generate unexpected diff output for merge
1914 changesets, as it will compare the merge changeset against its
1914 changesets, as it will compare the merge changeset against its
1915 first parent only.
1915 first parent only.
1916
1916
1917 Output may be to a file, in which case the name of the file is
1917 Output may be to a file, in which case the name of the file is
1918 given using a template string. See :hg:`help templates`. In addition
1918 given using a template string. See :hg:`help templates`. In addition
1919 to the common template keywords, the following formatting rules are
1919 to the common template keywords, the following formatting rules are
1920 supported:
1920 supported:
1921
1921
1922 :``%%``: literal "%" character
1922 :``%%``: literal "%" character
1923 :``%H``: changeset hash (40 hexadecimal digits)
1923 :``%H``: changeset hash (40 hexadecimal digits)
1924 :``%N``: number of patches being generated
1924 :``%N``: number of patches being generated
1925 :``%R``: changeset revision number
1925 :``%R``: changeset revision number
1926 :``%b``: basename of the exporting repository
1926 :``%b``: basename of the exporting repository
1927 :``%h``: short-form changeset hash (12 hexadecimal digits)
1927 :``%h``: short-form changeset hash (12 hexadecimal digits)
1928 :``%m``: first line of the commit message (only alphanumeric characters)
1928 :``%m``: first line of the commit message (only alphanumeric characters)
1929 :``%n``: zero-padded sequence number, starting at 1
1929 :``%n``: zero-padded sequence number, starting at 1
1930 :``%r``: zero-padded changeset revision number
1930 :``%r``: zero-padded changeset revision number
1931 :``\\``: literal "\\" character
1931 :``\\``: literal "\\" character
1932
1932
1933 Without the -a/--text option, export will avoid generating diffs
1933 Without the -a/--text option, export will avoid generating diffs
1934 of files it detects as binary. With -a, export will generate a
1934 of files it detects as binary. With -a, export will generate a
1935 diff anyway, probably with undesirable results.
1935 diff anyway, probably with undesirable results.
1936
1936
1937 Use the -g/--git option to generate diffs in the git extended diff
1937 Use the -g/--git option to generate diffs in the git extended diff
1938 format. See :hg:`help diffs` for more information.
1938 format. See :hg:`help diffs` for more information.
1939
1939
1940 With the --switch-parent option, the diff will be against the
1940 With the --switch-parent option, the diff will be against the
1941 second parent. It can be useful to review a merge.
1941 second parent. It can be useful to review a merge.
1942
1942
1943 .. container:: verbose
1943 .. container:: verbose
1944
1944
1945 Examples:
1945 Examples:
1946
1946
1947 - use export and import to transplant a bugfix to the current
1947 - use export and import to transplant a bugfix to the current
1948 branch::
1948 branch::
1949
1949
1950 hg export -r 9353 | hg import -
1950 hg export -r 9353 | hg import -
1951
1951
1952 - export all the changesets between two revisions to a file with
1952 - export all the changesets between two revisions to a file with
1953 rename information::
1953 rename information::
1954
1954
1955 hg export --git -r 123:150 > changes.txt
1955 hg export --git -r 123:150 > changes.txt
1956
1956
1957 - split outgoing changes into a series of patches with
1957 - split outgoing changes into a series of patches with
1958 descriptive names::
1958 descriptive names::
1959
1959
1960 hg export -r "outgoing()" -o "%n-%m.patch"
1960 hg export -r "outgoing()" -o "%n-%m.patch"
1961
1961
1962 Returns 0 on success.
1962 Returns 0 on success.
1963 """
1963 """
1964 opts = pycompat.byteskwargs(opts)
1964 opts = pycompat.byteskwargs(opts)
1965 changesets += tuple(opts.get('rev', []))
1965 changesets += tuple(opts.get('rev', []))
1966 if not changesets:
1966 if not changesets:
1967 changesets = ['.']
1967 changesets = ['.']
1968 repo = scmutil.unhidehashlikerevs(repo, changesets, 'nowarn')
1968 repo = scmutil.unhidehashlikerevs(repo, changesets, 'nowarn')
1969 revs = scmutil.revrange(repo, changesets)
1969 revs = scmutil.revrange(repo, changesets)
1970 if not revs:
1970 if not revs:
1971 raise error.Abort(_("export requires at least one changeset"))
1971 raise error.Abort(_("export requires at least one changeset"))
1972 if len(revs) > 1:
1972 if len(revs) > 1:
1973 ui.note(_('exporting patches:\n'))
1973 ui.note(_('exporting patches:\n'))
1974 else:
1974 else:
1975 ui.note(_('exporting patch:\n'))
1975 ui.note(_('exporting patch:\n'))
1976 ui.pager('export')
1976 ui.pager('export')
1977 cmdutil.export(repo, revs, fntemplate=opts.get('output'),
1977 cmdutil.export(repo, revs, fntemplate=opts.get('output'),
1978 switch_parent=opts.get('switch_parent'),
1978 switch_parent=opts.get('switch_parent'),
1979 opts=patch.diffallopts(ui, opts))
1979 opts=patch.diffallopts(ui, opts))
1980
1980
1981 @command('files',
1981 @command('files',
1982 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
1982 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
1983 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
1983 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
1984 ] + walkopts + formatteropts + subrepoopts,
1984 ] + walkopts + formatteropts + subrepoopts,
1985 _('[OPTION]... [FILE]...'), cmdtype=readonly)
1985 _('[OPTION]... [FILE]...'), cmdtype=readonly)
1986 def files(ui, repo, *pats, **opts):
1986 def files(ui, repo, *pats, **opts):
1987 """list tracked files
1987 """list tracked files
1988
1988
1989 Print files under Mercurial control in the working directory or
1989 Print files under Mercurial control in the working directory or
1990 specified revision for given files (excluding removed files).
1990 specified revision for given files (excluding removed files).
1991 Files can be specified as filenames or filesets.
1991 Files can be specified as filenames or filesets.
1992
1992
1993 If no files are given to match, this command prints the names
1993 If no files are given to match, this command prints the names
1994 of all files under Mercurial control.
1994 of all files under Mercurial control.
1995
1995
1996 .. container:: verbose
1996 .. container:: verbose
1997
1997
1998 Examples:
1998 Examples:
1999
1999
2000 - list all files under the current directory::
2000 - list all files under the current directory::
2001
2001
2002 hg files .
2002 hg files .
2003
2003
2004 - shows sizes and flags for current revision::
2004 - shows sizes and flags for current revision::
2005
2005
2006 hg files -vr .
2006 hg files -vr .
2007
2007
2008 - list all files named README::
2008 - list all files named README::
2009
2009
2010 hg files -I "**/README"
2010 hg files -I "**/README"
2011
2011
2012 - list all binary files::
2012 - list all binary files::
2013
2013
2014 hg files "set:binary()"
2014 hg files "set:binary()"
2015
2015
2016 - find files containing a regular expression::
2016 - find files containing a regular expression::
2017
2017
2018 hg files "set:grep('bob')"
2018 hg files "set:grep('bob')"
2019
2019
2020 - search tracked file contents with xargs and grep::
2020 - search tracked file contents with xargs and grep::
2021
2021
2022 hg files -0 | xargs -0 grep foo
2022 hg files -0 | xargs -0 grep foo
2023
2023
2024 See :hg:`help patterns` and :hg:`help filesets` for more information
2024 See :hg:`help patterns` and :hg:`help filesets` for more information
2025 on specifying file patterns.
2025 on specifying file patterns.
2026
2026
2027 Returns 0 if a match is found, 1 otherwise.
2027 Returns 0 if a match is found, 1 otherwise.
2028
2028
2029 """
2029 """
2030
2030
2031 opts = pycompat.byteskwargs(opts)
2031 opts = pycompat.byteskwargs(opts)
2032 rev = opts.get('rev')
2032 rev = opts.get('rev')
2033 if rev:
2033 if rev:
2034 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
2034 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
2035 ctx = scmutil.revsingle(repo, rev, None)
2035 ctx = scmutil.revsingle(repo, rev, None)
2036
2036
2037 end = '\n'
2037 end = '\n'
2038 if opts.get('print0'):
2038 if opts.get('print0'):
2039 end = '\0'
2039 end = '\0'
2040 fmt = '%s' + end
2040 fmt = '%s' + end
2041
2041
2042 m = scmutil.match(ctx, pats, opts)
2042 m = scmutil.match(ctx, pats, opts)
2043 ui.pager('files')
2043 ui.pager('files')
2044 with ui.formatter('files', opts) as fm:
2044 with ui.formatter('files', opts) as fm:
2045 return cmdutil.files(ui, ctx, m, fm, fmt, opts.get('subrepos'))
2045 return cmdutil.files(ui, ctx, m, fm, fmt, opts.get('subrepos'))
2046
2046
2047 @command(
2047 @command(
2048 '^forget',
2048 '^forget',
2049 walkopts + dryrunopts,
2049 walkopts + dryrunopts,
2050 _('[OPTION]... FILE...'), inferrepo=True)
2050 _('[OPTION]... FILE...'), inferrepo=True)
2051 def forget(ui, repo, *pats, **opts):
2051 def forget(ui, repo, *pats, **opts):
2052 """forget the specified files on the next commit
2052 """forget the specified files on the next commit
2053
2053
2054 Mark the specified files so they will no longer be tracked
2054 Mark the specified files so they will no longer be tracked
2055 after the next commit.
2055 after the next commit.
2056
2056
2057 This only removes files from the current branch, not from the
2057 This only removes files from the current branch, not from the
2058 entire project history, and it does not delete them from the
2058 entire project history, and it does not delete them from the
2059 working directory.
2059 working directory.
2060
2060
2061 To delete the file from the working directory, see :hg:`remove`.
2061 To delete the file from the working directory, see :hg:`remove`.
2062
2062
2063 To undo a forget before the next commit, see :hg:`add`.
2063 To undo a forget before the next commit, see :hg:`add`.
2064
2064
2065 .. container:: verbose
2065 .. container:: verbose
2066
2066
2067 Examples:
2067 Examples:
2068
2068
2069 - forget newly-added binary files::
2069 - forget newly-added binary files::
2070
2070
2071 hg forget "set:added() and binary()"
2071 hg forget "set:added() and binary()"
2072
2072
2073 - forget files that would be excluded by .hgignore::
2073 - forget files that would be excluded by .hgignore::
2074
2074
2075 hg forget "set:hgignore()"
2075 hg forget "set:hgignore()"
2076
2076
2077 Returns 0 on success.
2077 Returns 0 on success.
2078 """
2078 """
2079
2079
2080 opts = pycompat.byteskwargs(opts)
2080 opts = pycompat.byteskwargs(opts)
2081 if not pats:
2081 if not pats:
2082 raise error.Abort(_('no files specified'))
2082 raise error.Abort(_('no files specified'))
2083
2083
2084 m = scmutil.match(repo[None], pats, opts)
2084 m = scmutil.match(repo[None], pats, opts)
2085 dryrun = opts.get(r'dry_run')
2085 dryrun = opts.get(r'dry_run')
2086 rejected = cmdutil.forget(ui, repo, m, prefix="",
2086 rejected = cmdutil.forget(ui, repo, m, prefix="",
2087 explicitonly=False, dryrun=dryrun)[0]
2087 explicitonly=False, dryrun=dryrun)[0]
2088 return rejected and 1 or 0
2088 return rejected and 1 or 0
2089
2089
2090 @command(
2090 @command(
2091 'graft',
2091 'graft',
2092 [('r', 'rev', [], _('revisions to graft'), _('REV')),
2092 [('r', 'rev', [], _('revisions to graft'), _('REV')),
2093 ('c', 'continue', False, _('resume interrupted graft')),
2093 ('c', 'continue', False, _('resume interrupted graft')),
2094 ('e', 'edit', False, _('invoke editor on commit messages')),
2094 ('e', 'edit', False, _('invoke editor on commit messages')),
2095 ('', 'log', None, _('append graft info to log message')),
2095 ('', 'log', None, _('append graft info to log message')),
2096 ('f', 'force', False, _('force graft')),
2096 ('f', 'force', False, _('force graft')),
2097 ('D', 'currentdate', False,
2097 ('D', 'currentdate', False,
2098 _('record the current date as commit date')),
2098 _('record the current date as commit date')),
2099 ('U', 'currentuser', False,
2099 ('U', 'currentuser', False,
2100 _('record the current user as committer'), _('DATE'))]
2100 _('record the current user as committer'), _('DATE'))]
2101 + commitopts2 + mergetoolopts + dryrunopts,
2101 + commitopts2 + mergetoolopts + dryrunopts,
2102 _('[OPTION]... [-r REV]... REV...'))
2102 _('[OPTION]... [-r REV]... REV...'))
2103 def graft(ui, repo, *revs, **opts):
2103 def graft(ui, repo, *revs, **opts):
2104 '''copy changes from other branches onto the current branch
2104 '''copy changes from other branches onto the current branch
2105
2105
2106 This command uses Mercurial's merge logic to copy individual
2106 This command uses Mercurial's merge logic to copy individual
2107 changes from other branches without merging branches in the
2107 changes from other branches without merging branches in the
2108 history graph. This is sometimes known as 'backporting' or
2108 history graph. This is sometimes known as 'backporting' or
2109 'cherry-picking'. By default, graft will copy user, date, and
2109 'cherry-picking'. By default, graft will copy user, date, and
2110 description from the source changesets.
2110 description from the source changesets.
2111
2111
2112 Changesets that are ancestors of the current revision, that have
2112 Changesets that are ancestors of the current revision, that have
2113 already been grafted, or that are merges will be skipped.
2113 already been grafted, or that are merges will be skipped.
2114
2114
2115 If --log is specified, log messages will have a comment appended
2115 If --log is specified, log messages will have a comment appended
2116 of the form::
2116 of the form::
2117
2117
2118 (grafted from CHANGESETHASH)
2118 (grafted from CHANGESETHASH)
2119
2119
2120 If --force is specified, revisions will be grafted even if they
2120 If --force is specified, revisions will be grafted even if they
2121 are already ancestors of, or have been grafted to, the destination.
2121 are already ancestors of, or have been grafted to, the destination.
2122 This is useful when the revisions have since been backed out.
2122 This is useful when the revisions have since been backed out.
2123
2123
2124 If a graft merge results in conflicts, the graft process is
2124 If a graft merge results in conflicts, the graft process is
2125 interrupted so that the current merge can be manually resolved.
2125 interrupted so that the current merge can be manually resolved.
2126 Once all conflicts are addressed, the graft process can be
2126 Once all conflicts are addressed, the graft process can be
2127 continued with the -c/--continue option.
2127 continued with the -c/--continue option.
2128
2128
2129 .. note::
2129 .. note::
2130
2130
2131 The -c/--continue option does not reapply earlier options, except
2131 The -c/--continue option does not reapply earlier options, except
2132 for --force.
2132 for --force.
2133
2133
2134 .. container:: verbose
2134 .. container:: verbose
2135
2135
2136 Examples:
2136 Examples:
2137
2137
2138 - copy a single change to the stable branch and edit its description::
2138 - copy a single change to the stable branch and edit its description::
2139
2139
2140 hg update stable
2140 hg update stable
2141 hg graft --edit 9393
2141 hg graft --edit 9393
2142
2142
2143 - graft a range of changesets with one exception, updating dates::
2143 - graft a range of changesets with one exception, updating dates::
2144
2144
2145 hg graft -D "2085::2093 and not 2091"
2145 hg graft -D "2085::2093 and not 2091"
2146
2146
2147 - continue a graft after resolving conflicts::
2147 - continue a graft after resolving conflicts::
2148
2148
2149 hg graft -c
2149 hg graft -c
2150
2150
2151 - show the source of a grafted changeset::
2151 - show the source of a grafted changeset::
2152
2152
2153 hg log --debug -r .
2153 hg log --debug -r .
2154
2154
2155 - show revisions sorted by date::
2155 - show revisions sorted by date::
2156
2156
2157 hg log -r "sort(all(), date)"
2157 hg log -r "sort(all(), date)"
2158
2158
2159 See :hg:`help revisions` for more about specifying revisions.
2159 See :hg:`help revisions` for more about specifying revisions.
2160
2160
2161 Returns 0 on successful completion.
2161 Returns 0 on successful completion.
2162 '''
2162 '''
2163 with repo.wlock():
2163 with repo.wlock():
2164 return _dograft(ui, repo, *revs, **opts)
2164 return _dograft(ui, repo, *revs, **opts)
2165
2165
2166 def _dograft(ui, repo, *revs, **opts):
2166 def _dograft(ui, repo, *revs, **opts):
2167 opts = pycompat.byteskwargs(opts)
2167 opts = pycompat.byteskwargs(opts)
2168 if revs and opts.get('rev'):
2168 if revs and opts.get('rev'):
2169 ui.warn(_('warning: inconsistent use of --rev might give unexpected '
2169 ui.warn(_('warning: inconsistent use of --rev might give unexpected '
2170 'revision ordering!\n'))
2170 'revision ordering!\n'))
2171
2171
2172 revs = list(revs)
2172 revs = list(revs)
2173 revs.extend(opts.get('rev'))
2173 revs.extend(opts.get('rev'))
2174
2174
2175 if not opts.get('user') and opts.get('currentuser'):
2175 if not opts.get('user') and opts.get('currentuser'):
2176 opts['user'] = ui.username()
2176 opts['user'] = ui.username()
2177 if not opts.get('date') and opts.get('currentdate'):
2177 if not opts.get('date') and opts.get('currentdate'):
2178 opts['date'] = "%d %d" % dateutil.makedate()
2178 opts['date'] = "%d %d" % dateutil.makedate()
2179
2179
2180 editor = cmdutil.getcommiteditor(editform='graft',
2180 editor = cmdutil.getcommiteditor(editform='graft',
2181 **pycompat.strkwargs(opts))
2181 **pycompat.strkwargs(opts))
2182
2182
2183 cont = False
2183 cont = False
2184 if opts.get('continue'):
2184 if opts.get('continue'):
2185 cont = True
2185 cont = True
2186 if revs:
2186 if revs:
2187 raise error.Abort(_("can't specify --continue and revisions"))
2187 raise error.Abort(_("can't specify --continue and revisions"))
2188 # read in unfinished revisions
2188 # read in unfinished revisions
2189 try:
2189 try:
2190 nodes = repo.vfs.read('graftstate').splitlines()
2190 nodes = repo.vfs.read('graftstate').splitlines()
2191 revs = [repo[node].rev() for node in nodes]
2191 revs = [repo[node].rev() for node in nodes]
2192 except IOError as inst:
2192 except IOError as inst:
2193 if inst.errno != errno.ENOENT:
2193 if inst.errno != errno.ENOENT:
2194 raise
2194 raise
2195 cmdutil.wrongtooltocontinue(repo, _('graft'))
2195 cmdutil.wrongtooltocontinue(repo, _('graft'))
2196 else:
2196 else:
2197 if not revs:
2197 if not revs:
2198 raise error.Abort(_('no revisions specified'))
2198 raise error.Abort(_('no revisions specified'))
2199 cmdutil.checkunfinished(repo)
2199 cmdutil.checkunfinished(repo)
2200 cmdutil.bailifchanged(repo)
2200 cmdutil.bailifchanged(repo)
2201 revs = scmutil.revrange(repo, revs)
2201 revs = scmutil.revrange(repo, revs)
2202
2202
2203 skipped = set()
2203 skipped = set()
2204 # check for merges
2204 # check for merges
2205 for rev in repo.revs('%ld and merge()', revs):
2205 for rev in repo.revs('%ld and merge()', revs):
2206 ui.warn(_('skipping ungraftable merge revision %d\n') % rev)
2206 ui.warn(_('skipping ungraftable merge revision %d\n') % rev)
2207 skipped.add(rev)
2207 skipped.add(rev)
2208 revs = [r for r in revs if r not in skipped]
2208 revs = [r for r in revs if r not in skipped]
2209 if not revs:
2209 if not revs:
2210 return -1
2210 return -1
2211
2211
2212 # Don't check in the --continue case, in effect retaining --force across
2212 # Don't check in the --continue case, in effect retaining --force across
2213 # --continues. That's because without --force, any revisions we decided to
2213 # --continues. That's because without --force, any revisions we decided to
2214 # skip would have been filtered out here, so they wouldn't have made their
2214 # skip would have been filtered out here, so they wouldn't have made their
2215 # way to the graftstate. With --force, any revisions we would have otherwise
2215 # way to the graftstate. With --force, any revisions we would have otherwise
2216 # skipped would not have been filtered out, and if they hadn't been applied
2216 # skipped would not have been filtered out, and if they hadn't been applied
2217 # already, they'd have been in the graftstate.
2217 # already, they'd have been in the graftstate.
2218 if not (cont or opts.get('force')):
2218 if not (cont or opts.get('force')):
2219 # check for ancestors of dest branch
2219 # check for ancestors of dest branch
2220 crev = repo['.'].rev()
2220 crev = repo['.'].rev()
2221 ancestors = repo.changelog.ancestors([crev], inclusive=True)
2221 ancestors = repo.changelog.ancestors([crev], inclusive=True)
2222 # XXX make this lazy in the future
2222 # XXX make this lazy in the future
2223 # don't mutate while iterating, create a copy
2223 # don't mutate while iterating, create a copy
2224 for rev in list(revs):
2224 for rev in list(revs):
2225 if rev in ancestors:
2225 if rev in ancestors:
2226 ui.warn(_('skipping ancestor revision %d:%s\n') %
2226 ui.warn(_('skipping ancestor revision %d:%s\n') %
2227 (rev, repo[rev]))
2227 (rev, repo[rev]))
2228 # XXX remove on list is slow
2228 # XXX remove on list is slow
2229 revs.remove(rev)
2229 revs.remove(rev)
2230 if not revs:
2230 if not revs:
2231 return -1
2231 return -1
2232
2232
2233 # analyze revs for earlier grafts
2233 # analyze revs for earlier grafts
2234 ids = {}
2234 ids = {}
2235 for ctx in repo.set("%ld", revs):
2235 for ctx in repo.set("%ld", revs):
2236 ids[ctx.hex()] = ctx.rev()
2236 ids[ctx.hex()] = ctx.rev()
2237 n = ctx.extra().get('source')
2237 n = ctx.extra().get('source')
2238 if n:
2238 if n:
2239 ids[n] = ctx.rev()
2239 ids[n] = ctx.rev()
2240
2240
2241 # check ancestors for earlier grafts
2241 # check ancestors for earlier grafts
2242 ui.debug('scanning for duplicate grafts\n')
2242 ui.debug('scanning for duplicate grafts\n')
2243
2243
2244 # The only changesets we can be sure doesn't contain grafts of any
2244 # The only changesets we can be sure doesn't contain grafts of any
2245 # revs, are the ones that are common ancestors of *all* revs:
2245 # revs, are the ones that are common ancestors of *all* revs:
2246 for rev in repo.revs('only(%d,ancestor(%ld))', crev, revs):
2246 for rev in repo.revs('only(%d,ancestor(%ld))', crev, revs):
2247 ctx = repo[rev]
2247 ctx = repo[rev]
2248 n = ctx.extra().get('source')
2248 n = ctx.extra().get('source')
2249 if n in ids:
2249 if n in ids:
2250 try:
2250 try:
2251 r = repo[n].rev()
2251 r = repo[n].rev()
2252 except error.RepoLookupError:
2252 except error.RepoLookupError:
2253 r = None
2253 r = None
2254 if r in revs:
2254 if r in revs:
2255 ui.warn(_('skipping revision %d:%s '
2255 ui.warn(_('skipping revision %d:%s '
2256 '(already grafted to %d:%s)\n')
2256 '(already grafted to %d:%s)\n')
2257 % (r, repo[r], rev, ctx))
2257 % (r, repo[r], rev, ctx))
2258 revs.remove(r)
2258 revs.remove(r)
2259 elif ids[n] in revs:
2259 elif ids[n] in revs:
2260 if r is None:
2260 if r is None:
2261 ui.warn(_('skipping already grafted revision %d:%s '
2261 ui.warn(_('skipping already grafted revision %d:%s '
2262 '(%d:%s also has unknown origin %s)\n')
2262 '(%d:%s also has unknown origin %s)\n')
2263 % (ids[n], repo[ids[n]], rev, ctx, n[:12]))
2263 % (ids[n], repo[ids[n]], rev, ctx, n[:12]))
2264 else:
2264 else:
2265 ui.warn(_('skipping already grafted revision %d:%s '
2265 ui.warn(_('skipping already grafted revision %d:%s '
2266 '(%d:%s also has origin %d:%s)\n')
2266 '(%d:%s also has origin %d:%s)\n')
2267 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12]))
2267 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12]))
2268 revs.remove(ids[n])
2268 revs.remove(ids[n])
2269 elif ctx.hex() in ids:
2269 elif ctx.hex() in ids:
2270 r = ids[ctx.hex()]
2270 r = ids[ctx.hex()]
2271 ui.warn(_('skipping already grafted revision %d:%s '
2271 ui.warn(_('skipping already grafted revision %d:%s '
2272 '(was grafted from %d:%s)\n') %
2272 '(was grafted from %d:%s)\n') %
2273 (r, repo[r], rev, ctx))
2273 (r, repo[r], rev, ctx))
2274 revs.remove(r)
2274 revs.remove(r)
2275 if not revs:
2275 if not revs:
2276 return -1
2276 return -1
2277
2277
2278 for pos, ctx in enumerate(repo.set("%ld", revs)):
2278 for pos, ctx in enumerate(repo.set("%ld", revs)):
2279 desc = '%d:%s "%s"' % (ctx.rev(), ctx,
2279 desc = '%d:%s "%s"' % (ctx.rev(), ctx,
2280 ctx.description().split('\n', 1)[0])
2280 ctx.description().split('\n', 1)[0])
2281 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
2281 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
2282 if names:
2282 if names:
2283 desc += ' (%s)' % ' '.join(names)
2283 desc += ' (%s)' % ' '.join(names)
2284 ui.status(_('grafting %s\n') % desc)
2284 ui.status(_('grafting %s\n') % desc)
2285 if opts.get('dry_run'):
2285 if opts.get('dry_run'):
2286 continue
2286 continue
2287
2287
2288 source = ctx.extra().get('source')
2288 source = ctx.extra().get('source')
2289 extra = {}
2289 extra = {}
2290 if source:
2290 if source:
2291 extra['source'] = source
2291 extra['source'] = source
2292 extra['intermediate-source'] = ctx.hex()
2292 extra['intermediate-source'] = ctx.hex()
2293 else:
2293 else:
2294 extra['source'] = ctx.hex()
2294 extra['source'] = ctx.hex()
2295 user = ctx.user()
2295 user = ctx.user()
2296 if opts.get('user'):
2296 if opts.get('user'):
2297 user = opts['user']
2297 user = opts['user']
2298 date = ctx.date()
2298 date = ctx.date()
2299 if opts.get('date'):
2299 if opts.get('date'):
2300 date = opts['date']
2300 date = opts['date']
2301 message = ctx.description()
2301 message = ctx.description()
2302 if opts.get('log'):
2302 if opts.get('log'):
2303 message += '\n(grafted from %s)' % ctx.hex()
2303 message += '\n(grafted from %s)' % ctx.hex()
2304
2304
2305 # we don't merge the first commit when continuing
2305 # we don't merge the first commit when continuing
2306 if not cont:
2306 if not cont:
2307 # perform the graft merge with p1(rev) as 'ancestor'
2307 # perform the graft merge with p1(rev) as 'ancestor'
2308 try:
2308 try:
2309 # ui.forcemerge is an internal variable, do not document
2309 # ui.forcemerge is an internal variable, do not document
2310 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
2310 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
2311 'graft')
2311 'graft')
2312 stats = mergemod.graft(repo, ctx, ctx.p1(),
2312 stats = mergemod.graft(repo, ctx, ctx.p1(),
2313 ['local', 'graft'])
2313 ['local', 'graft'])
2314 finally:
2314 finally:
2315 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
2315 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
2316 # report any conflicts
2316 # report any conflicts
2317 if stats.unresolvedcount > 0:
2317 if stats.unresolvedcount > 0:
2318 # write out state for --continue
2318 # write out state for --continue
2319 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
2319 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
2320 repo.vfs.write('graftstate', ''.join(nodelines))
2320 repo.vfs.write('graftstate', ''.join(nodelines))
2321 extra = ''
2321 extra = ''
2322 if opts.get('user'):
2322 if opts.get('user'):
2323 extra += ' --user %s' % procutil.shellquote(opts['user'])
2323 extra += ' --user %s' % procutil.shellquote(opts['user'])
2324 if opts.get('date'):
2324 if opts.get('date'):
2325 extra += ' --date %s' % procutil.shellquote(opts['date'])
2325 extra += ' --date %s' % procutil.shellquote(opts['date'])
2326 if opts.get('log'):
2326 if opts.get('log'):
2327 extra += ' --log'
2327 extra += ' --log'
2328 hint=_("use 'hg resolve' and 'hg graft --continue%s'") % extra
2328 hint=_("use 'hg resolve' and 'hg graft --continue%s'") % extra
2329 raise error.Abort(
2329 raise error.Abort(
2330 _("unresolved conflicts, can't continue"),
2330 _("unresolved conflicts, can't continue"),
2331 hint=hint)
2331 hint=hint)
2332 else:
2332 else:
2333 cont = False
2333 cont = False
2334
2334
2335 # commit
2335 # commit
2336 node = repo.commit(text=message, user=user,
2336 node = repo.commit(text=message, user=user,
2337 date=date, extra=extra, editor=editor)
2337 date=date, extra=extra, editor=editor)
2338 if node is None:
2338 if node is None:
2339 ui.warn(
2339 ui.warn(
2340 _('note: graft of %d:%s created no changes to commit\n') %
2340 _('note: graft of %d:%s created no changes to commit\n') %
2341 (ctx.rev(), ctx))
2341 (ctx.rev(), ctx))
2342
2342
2343 # remove state when we complete successfully
2343 # remove state when we complete successfully
2344 if not opts.get('dry_run'):
2344 if not opts.get('dry_run'):
2345 repo.vfs.unlinkpath('graftstate', ignoremissing=True)
2345 repo.vfs.unlinkpath('graftstate', ignoremissing=True)
2346
2346
2347 return 0
2347 return 0
2348
2348
2349 @command('grep',
2349 @command('grep',
2350 [('0', 'print0', None, _('end fields with NUL')),
2350 [('0', 'print0', None, _('end fields with NUL')),
2351 ('', 'all', None, _('print all revisions that match')),
2351 ('', 'all', None, _('print all revisions that match')),
2352 ('a', 'text', None, _('treat all files as text')),
2352 ('a', 'text', None, _('treat all files as text')),
2353 ('f', 'follow', None,
2353 ('f', 'follow', None,
2354 _('follow changeset history,'
2354 _('follow changeset history,'
2355 ' or file history across copies and renames')),
2355 ' or file history across copies and renames')),
2356 ('i', 'ignore-case', None, _('ignore case when matching')),
2356 ('i', 'ignore-case', None, _('ignore case when matching')),
2357 ('l', 'files-with-matches', None,
2357 ('l', 'files-with-matches', None,
2358 _('print only filenames and revisions that match')),
2358 _('print only filenames and revisions that match')),
2359 ('n', 'line-number', None, _('print matching line numbers')),
2359 ('n', 'line-number', None, _('print matching line numbers')),
2360 ('r', 'rev', [],
2360 ('r', 'rev', [],
2361 _('only search files changed within revision range'), _('REV')),
2361 _('only search files changed within revision range'), _('REV')),
2362 ('u', 'user', None, _('list the author (long with -v)')),
2362 ('u', 'user', None, _('list the author (long with -v)')),
2363 ('d', 'date', None, _('list the date (short with -q)')),
2363 ('d', 'date', None, _('list the date (short with -q)')),
2364 ] + formatteropts + walkopts,
2364 ] + formatteropts + walkopts,
2365 _('[OPTION]... PATTERN [FILE]...'),
2365 _('[OPTION]... PATTERN [FILE]...'),
2366 inferrepo=True, cmdtype=readonly)
2366 inferrepo=True, cmdtype=readonly)
2367 def grep(ui, repo, pattern, *pats, **opts):
2367 def grep(ui, repo, pattern, *pats, **opts):
2368 """search revision history for a pattern in specified files
2368 """search revision history for a pattern in specified files
2369
2369
2370 Search revision history for a regular expression in the specified
2370 Search revision history for a regular expression in the specified
2371 files or the entire project.
2371 files or the entire project.
2372
2372
2373 By default, grep prints the most recent revision number for each
2373 By default, grep prints the most recent revision number for each
2374 file in which it finds a match. To get it to print every revision
2374 file in which it finds a match. To get it to print every revision
2375 that contains a change in match status ("-" for a match that becomes
2375 that contains a change in match status ("-" for a match that becomes
2376 a non-match, or "+" for a non-match that becomes a match), use the
2376 a non-match, or "+" for a non-match that becomes a match), use the
2377 --all flag.
2377 --all flag.
2378
2378
2379 PATTERN can be any Python (roughly Perl-compatible) regular
2379 PATTERN can be any Python (roughly Perl-compatible) regular
2380 expression.
2380 expression.
2381
2381
2382 If no FILEs are specified (and -f/--follow isn't set), all files in
2382 If no FILEs are specified (and -f/--follow isn't set), all files in
2383 the repository are searched, including those that don't exist in the
2383 the repository are searched, including those that don't exist in the
2384 current branch or have been deleted in a prior changeset.
2384 current branch or have been deleted in a prior changeset.
2385
2385
2386 Returns 0 if a match is found, 1 otherwise.
2386 Returns 0 if a match is found, 1 otherwise.
2387 """
2387 """
2388 opts = pycompat.byteskwargs(opts)
2388 opts = pycompat.byteskwargs(opts)
2389 reflags = re.M
2389 reflags = re.M
2390 if opts.get('ignore_case'):
2390 if opts.get('ignore_case'):
2391 reflags |= re.I
2391 reflags |= re.I
2392 try:
2392 try:
2393 regexp = util.re.compile(pattern, reflags)
2393 regexp = util.re.compile(pattern, reflags)
2394 except re.error as inst:
2394 except re.error as inst:
2395 ui.warn(_("grep: invalid match pattern: %s\n") % pycompat.bytestr(inst))
2395 ui.warn(_("grep: invalid match pattern: %s\n") % pycompat.bytestr(inst))
2396 return 1
2396 return 1
2397 sep, eol = ':', '\n'
2397 sep, eol = ':', '\n'
2398 if opts.get('print0'):
2398 if opts.get('print0'):
2399 sep = eol = '\0'
2399 sep = eol = '\0'
2400
2400
2401 getfile = util.lrucachefunc(repo.file)
2401 getfile = util.lrucachefunc(repo.file)
2402
2402
2403 def matchlines(body):
2403 def matchlines(body):
2404 begin = 0
2404 begin = 0
2405 linenum = 0
2405 linenum = 0
2406 while begin < len(body):
2406 while begin < len(body):
2407 match = regexp.search(body, begin)
2407 match = regexp.search(body, begin)
2408 if not match:
2408 if not match:
2409 break
2409 break
2410 mstart, mend = match.span()
2410 mstart, mend = match.span()
2411 linenum += body.count('\n', begin, mstart) + 1
2411 linenum += body.count('\n', begin, mstart) + 1
2412 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2412 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2413 begin = body.find('\n', mend) + 1 or len(body) + 1
2413 begin = body.find('\n', mend) + 1 or len(body) + 1
2414 lend = begin - 1
2414 lend = begin - 1
2415 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2415 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2416
2416
2417 class linestate(object):
2417 class linestate(object):
2418 def __init__(self, line, linenum, colstart, colend):
2418 def __init__(self, line, linenum, colstart, colend):
2419 self.line = line
2419 self.line = line
2420 self.linenum = linenum
2420 self.linenum = linenum
2421 self.colstart = colstart
2421 self.colstart = colstart
2422 self.colend = colend
2422 self.colend = colend
2423
2423
2424 def __hash__(self):
2424 def __hash__(self):
2425 return hash((self.linenum, self.line))
2425 return hash((self.linenum, self.line))
2426
2426
2427 def __eq__(self, other):
2427 def __eq__(self, other):
2428 return self.line == other.line
2428 return self.line == other.line
2429
2429
2430 def findpos(self):
2430 def findpos(self):
2431 """Iterate all (start, end) indices of matches"""
2431 """Iterate all (start, end) indices of matches"""
2432 yield self.colstart, self.colend
2432 yield self.colstart, self.colend
2433 p = self.colend
2433 p = self.colend
2434 while p < len(self.line):
2434 while p < len(self.line):
2435 m = regexp.search(self.line, p)
2435 m = regexp.search(self.line, p)
2436 if not m:
2436 if not m:
2437 break
2437 break
2438 yield m.span()
2438 yield m.span()
2439 p = m.end()
2439 p = m.end()
2440
2440
2441 matches = {}
2441 matches = {}
2442 copies = {}
2442 copies = {}
2443 def grepbody(fn, rev, body):
2443 def grepbody(fn, rev, body):
2444 matches[rev].setdefault(fn, [])
2444 matches[rev].setdefault(fn, [])
2445 m = matches[rev][fn]
2445 m = matches[rev][fn]
2446 for lnum, cstart, cend, line in matchlines(body):
2446 for lnum, cstart, cend, line in matchlines(body):
2447 s = linestate(line, lnum, cstart, cend)
2447 s = linestate(line, lnum, cstart, cend)
2448 m.append(s)
2448 m.append(s)
2449
2449
2450 def difflinestates(a, b):
2450 def difflinestates(a, b):
2451 sm = difflib.SequenceMatcher(None, a, b)
2451 sm = difflib.SequenceMatcher(None, a, b)
2452 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2452 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2453 if tag == 'insert':
2453 if tag == 'insert':
2454 for i in xrange(blo, bhi):
2454 for i in xrange(blo, bhi):
2455 yield ('+', b[i])
2455 yield ('+', b[i])
2456 elif tag == 'delete':
2456 elif tag == 'delete':
2457 for i in xrange(alo, ahi):
2457 for i in xrange(alo, ahi):
2458 yield ('-', a[i])
2458 yield ('-', a[i])
2459 elif tag == 'replace':
2459 elif tag == 'replace':
2460 for i in xrange(alo, ahi):
2460 for i in xrange(alo, ahi):
2461 yield ('-', a[i])
2461 yield ('-', a[i])
2462 for i in xrange(blo, bhi):
2462 for i in xrange(blo, bhi):
2463 yield ('+', b[i])
2463 yield ('+', b[i])
2464
2464
2465 def display(fm, fn, ctx, pstates, states):
2465 def display(fm, fn, ctx, pstates, states):
2466 rev = ctx.rev()
2466 rev = ctx.rev()
2467 if fm.isplain():
2467 if fm.isplain():
2468 formatuser = ui.shortuser
2468 formatuser = ui.shortuser
2469 else:
2469 else:
2470 formatuser = str
2470 formatuser = str
2471 if ui.quiet:
2471 if ui.quiet:
2472 datefmt = '%Y-%m-%d'
2472 datefmt = '%Y-%m-%d'
2473 else:
2473 else:
2474 datefmt = '%a %b %d %H:%M:%S %Y %1%2'
2474 datefmt = '%a %b %d %H:%M:%S %Y %1%2'
2475 found = False
2475 found = False
2476 @util.cachefunc
2476 @util.cachefunc
2477 def binary():
2477 def binary():
2478 flog = getfile(fn)
2478 flog = getfile(fn)
2479 return stringutil.binary(flog.read(ctx.filenode(fn)))
2479 return stringutil.binary(flog.read(ctx.filenode(fn)))
2480
2480
2481 fieldnamemap = {'filename': 'file', 'linenumber': 'line_number'}
2481 fieldnamemap = {'filename': 'file', 'linenumber': 'line_number'}
2482 if opts.get('all'):
2482 if opts.get('all'):
2483 iter = difflinestates(pstates, states)
2483 iter = difflinestates(pstates, states)
2484 else:
2484 else:
2485 iter = [('', l) for l in states]
2485 iter = [('', l) for l in states]
2486 for change, l in iter:
2486 for change, l in iter:
2487 fm.startitem()
2487 fm.startitem()
2488 fm.data(node=fm.hexfunc(ctx.node()))
2488 fm.data(node=fm.hexfunc(ctx.node()))
2489 cols = [
2489 cols = [
2490 ('filename', fn, True),
2490 ('filename', fn, True),
2491 ('rev', rev, True),
2491 ('rev', rev, True),
2492 ('linenumber', l.linenum, opts.get('line_number')),
2492 ('linenumber', l.linenum, opts.get('line_number')),
2493 ]
2493 ]
2494 if opts.get('all'):
2494 if opts.get('all'):
2495 cols.append(('change', change, True))
2495 cols.append(('change', change, True))
2496 cols.extend([
2496 cols.extend([
2497 ('user', formatuser(ctx.user()), opts.get('user')),
2497 ('user', formatuser(ctx.user()), opts.get('user')),
2498 ('date', fm.formatdate(ctx.date(), datefmt), opts.get('date')),
2498 ('date', fm.formatdate(ctx.date(), datefmt), opts.get('date')),
2499 ])
2499 ])
2500 lastcol = next(name for name, data, cond in reversed(cols) if cond)
2500 lastcol = next(name for name, data, cond in reversed(cols) if cond)
2501 for name, data, cond in cols:
2501 for name, data, cond in cols:
2502 field = fieldnamemap.get(name, name)
2502 field = fieldnamemap.get(name, name)
2503 fm.condwrite(cond, field, '%s', data, label='grep.%s' % name)
2503 fm.condwrite(cond, field, '%s', data, label='grep.%s' % name)
2504 if cond and name != lastcol:
2504 if cond and name != lastcol:
2505 fm.plain(sep, label='grep.sep')
2505 fm.plain(sep, label='grep.sep')
2506 if not opts.get('files_with_matches'):
2506 if not opts.get('files_with_matches'):
2507 fm.plain(sep, label='grep.sep')
2507 fm.plain(sep, label='grep.sep')
2508 if not opts.get('text') and binary():
2508 if not opts.get('text') and binary():
2509 fm.plain(_(" Binary file matches"))
2509 fm.plain(_(" Binary file matches"))
2510 else:
2510 else:
2511 displaymatches(fm.nested('texts'), l)
2511 displaymatches(fm.nested('texts'), l)
2512 fm.plain(eol)
2512 fm.plain(eol)
2513 found = True
2513 found = True
2514 if opts.get('files_with_matches'):
2514 if opts.get('files_with_matches'):
2515 break
2515 break
2516 return found
2516 return found
2517
2517
2518 def displaymatches(fm, l):
2518 def displaymatches(fm, l):
2519 p = 0
2519 p = 0
2520 for s, e in l.findpos():
2520 for s, e in l.findpos():
2521 if p < s:
2521 if p < s:
2522 fm.startitem()
2522 fm.startitem()
2523 fm.write('text', '%s', l.line[p:s])
2523 fm.write('text', '%s', l.line[p:s])
2524 fm.data(matched=False)
2524 fm.data(matched=False)
2525 fm.startitem()
2525 fm.startitem()
2526 fm.write('text', '%s', l.line[s:e], label='grep.match')
2526 fm.write('text', '%s', l.line[s:e], label='grep.match')
2527 fm.data(matched=True)
2527 fm.data(matched=True)
2528 p = e
2528 p = e
2529 if p < len(l.line):
2529 if p < len(l.line):
2530 fm.startitem()
2530 fm.startitem()
2531 fm.write('text', '%s', l.line[p:])
2531 fm.write('text', '%s', l.line[p:])
2532 fm.data(matched=False)
2532 fm.data(matched=False)
2533 fm.end()
2533 fm.end()
2534
2534
2535 skip = {}
2535 skip = {}
2536 revfiles = {}
2536 revfiles = {}
2537 match = scmutil.match(repo[None], pats, opts)
2537 match = scmutil.match(repo[None], pats, opts)
2538 found = False
2538 found = False
2539 follow = opts.get('follow')
2539 follow = opts.get('follow')
2540
2540
2541 def prep(ctx, fns):
2541 def prep(ctx, fns):
2542 rev = ctx.rev()
2542 rev = ctx.rev()
2543 pctx = ctx.p1()
2543 pctx = ctx.p1()
2544 parent = pctx.rev()
2544 parent = pctx.rev()
2545 matches.setdefault(rev, {})
2545 matches.setdefault(rev, {})
2546 matches.setdefault(parent, {})
2546 matches.setdefault(parent, {})
2547 files = revfiles.setdefault(rev, [])
2547 files = revfiles.setdefault(rev, [])
2548 for fn in fns:
2548 for fn in fns:
2549 flog = getfile(fn)
2549 flog = getfile(fn)
2550 try:
2550 try:
2551 fnode = ctx.filenode(fn)
2551 fnode = ctx.filenode(fn)
2552 except error.LookupError:
2552 except error.LookupError:
2553 continue
2553 continue
2554
2554
2555 copied = flog.renamed(fnode)
2555 copied = flog.renamed(fnode)
2556 copy = follow and copied and copied[0]
2556 copy = follow and copied and copied[0]
2557 if copy:
2557 if copy:
2558 copies.setdefault(rev, {})[fn] = copy
2558 copies.setdefault(rev, {})[fn] = copy
2559 if fn in skip:
2559 if fn in skip:
2560 if copy:
2560 if copy:
2561 skip[copy] = True
2561 skip[copy] = True
2562 continue
2562 continue
2563 files.append(fn)
2563 files.append(fn)
2564
2564
2565 if fn not in matches[rev]:
2565 if fn not in matches[rev]:
2566 grepbody(fn, rev, flog.read(fnode))
2566 grepbody(fn, rev, flog.read(fnode))
2567
2567
2568 pfn = copy or fn
2568 pfn = copy or fn
2569 if pfn not in matches[parent]:
2569 if pfn not in matches[parent]:
2570 try:
2570 try:
2571 fnode = pctx.filenode(pfn)
2571 fnode = pctx.filenode(pfn)
2572 grepbody(pfn, parent, flog.read(fnode))
2572 grepbody(pfn, parent, flog.read(fnode))
2573 except error.LookupError:
2573 except error.LookupError:
2574 pass
2574 pass
2575
2575
2576 ui.pager('grep')
2576 ui.pager('grep')
2577 fm = ui.formatter('grep', opts)
2577 fm = ui.formatter('grep', opts)
2578 for ctx in cmdutil.walkchangerevs(repo, match, opts, prep):
2578 for ctx in cmdutil.walkchangerevs(repo, match, opts, prep):
2579 rev = ctx.rev()
2579 rev = ctx.rev()
2580 parent = ctx.p1().rev()
2580 parent = ctx.p1().rev()
2581 for fn in sorted(revfiles.get(rev, [])):
2581 for fn in sorted(revfiles.get(rev, [])):
2582 states = matches[rev][fn]
2582 states = matches[rev][fn]
2583 copy = copies.get(rev, {}).get(fn)
2583 copy = copies.get(rev, {}).get(fn)
2584 if fn in skip:
2584 if fn in skip:
2585 if copy:
2585 if copy:
2586 skip[copy] = True
2586 skip[copy] = True
2587 continue
2587 continue
2588 pstates = matches.get(parent, {}).get(copy or fn, [])
2588 pstates = matches.get(parent, {}).get(copy or fn, [])
2589 if pstates or states:
2589 if pstates or states:
2590 r = display(fm, fn, ctx, pstates, states)
2590 r = display(fm, fn, ctx, pstates, states)
2591 found = found or r
2591 found = found or r
2592 if r and not opts.get('all'):
2592 if r and not opts.get('all'):
2593 skip[fn] = True
2593 skip[fn] = True
2594 if copy:
2594 if copy:
2595 skip[copy] = True
2595 skip[copy] = True
2596 del revfiles[rev]
2596 del revfiles[rev]
2597 # We will keep the matches dict for the duration of the window
2597 # We will keep the matches dict for the duration of the window
2598 # clear the matches dict once the window is over
2598 # clear the matches dict once the window is over
2599 if not revfiles:
2599 if not revfiles:
2600 matches.clear()
2600 matches.clear()
2601 fm.end()
2601 fm.end()
2602
2602
2603 return not found
2603 return not found
2604
2604
2605 @command('heads',
2605 @command('heads',
2606 [('r', 'rev', '',
2606 [('r', 'rev', '',
2607 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2607 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2608 ('t', 'topo', False, _('show topological heads only')),
2608 ('t', 'topo', False, _('show topological heads only')),
2609 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2609 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2610 ('c', 'closed', False, _('show normal and closed branch heads')),
2610 ('c', 'closed', False, _('show normal and closed branch heads')),
2611 ] + templateopts,
2611 ] + templateopts,
2612 _('[-ct] [-r STARTREV] [REV]...'), cmdtype=readonly)
2612 _('[-ct] [-r STARTREV] [REV]...'), cmdtype=readonly)
2613 def heads(ui, repo, *branchrevs, **opts):
2613 def heads(ui, repo, *branchrevs, **opts):
2614 """show branch heads
2614 """show branch heads
2615
2615
2616 With no arguments, show all open branch heads in the repository.
2616 With no arguments, show all open branch heads in the repository.
2617 Branch heads are changesets that have no descendants on the
2617 Branch heads are changesets that have no descendants on the
2618 same branch. They are where development generally takes place and
2618 same branch. They are where development generally takes place and
2619 are the usual targets for update and merge operations.
2619 are the usual targets for update and merge operations.
2620
2620
2621 If one or more REVs are given, only open branch heads on the
2621 If one or more REVs are given, only open branch heads on the
2622 branches associated with the specified changesets are shown. This
2622 branches associated with the specified changesets are shown. This
2623 means that you can use :hg:`heads .` to see the heads on the
2623 means that you can use :hg:`heads .` to see the heads on the
2624 currently checked-out branch.
2624 currently checked-out branch.
2625
2625
2626 If -c/--closed is specified, also show branch heads marked closed
2626 If -c/--closed is specified, also show branch heads marked closed
2627 (see :hg:`commit --close-branch`).
2627 (see :hg:`commit --close-branch`).
2628
2628
2629 If STARTREV is specified, only those heads that are descendants of
2629 If STARTREV is specified, only those heads that are descendants of
2630 STARTREV will be displayed.
2630 STARTREV will be displayed.
2631
2631
2632 If -t/--topo is specified, named branch mechanics will be ignored and only
2632 If -t/--topo is specified, named branch mechanics will be ignored and only
2633 topological heads (changesets with no children) will be shown.
2633 topological heads (changesets with no children) will be shown.
2634
2634
2635 Returns 0 if matching heads are found, 1 if not.
2635 Returns 0 if matching heads are found, 1 if not.
2636 """
2636 """
2637
2637
2638 opts = pycompat.byteskwargs(opts)
2638 opts = pycompat.byteskwargs(opts)
2639 start = None
2639 start = None
2640 rev = opts.get('rev')
2640 rev = opts.get('rev')
2641 if rev:
2641 if rev:
2642 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
2642 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
2643 start = scmutil.revsingle(repo, rev, None).node()
2643 start = scmutil.revsingle(repo, rev, None).node()
2644
2644
2645 if opts.get('topo'):
2645 if opts.get('topo'):
2646 heads = [repo[h] for h in repo.heads(start)]
2646 heads = [repo[h] for h in repo.heads(start)]
2647 else:
2647 else:
2648 heads = []
2648 heads = []
2649 for branch in repo.branchmap():
2649 for branch in repo.branchmap():
2650 heads += repo.branchheads(branch, start, opts.get('closed'))
2650 heads += repo.branchheads(branch, start, opts.get('closed'))
2651 heads = [repo[h] for h in heads]
2651 heads = [repo[h] for h in heads]
2652
2652
2653 if branchrevs:
2653 if branchrevs:
2654 branches = set(repo[br].branch() for br in branchrevs)
2654 branches = set(repo[br].branch() for br in branchrevs)
2655 heads = [h for h in heads if h.branch() in branches]
2655 heads = [h for h in heads if h.branch() in branches]
2656
2656
2657 if opts.get('active') and branchrevs:
2657 if opts.get('active') and branchrevs:
2658 dagheads = repo.heads(start)
2658 dagheads = repo.heads(start)
2659 heads = [h for h in heads if h.node() in dagheads]
2659 heads = [h for h in heads if h.node() in dagheads]
2660
2660
2661 if branchrevs:
2661 if branchrevs:
2662 haveheads = set(h.branch() for h in heads)
2662 haveheads = set(h.branch() for h in heads)
2663 if branches - haveheads:
2663 if branches - haveheads:
2664 headless = ', '.join(b for b in branches - haveheads)
2664 headless = ', '.join(b for b in branches - haveheads)
2665 msg = _('no open branch heads found on branches %s')
2665 msg = _('no open branch heads found on branches %s')
2666 if opts.get('rev'):
2666 if opts.get('rev'):
2667 msg += _(' (started at %s)') % opts['rev']
2667 msg += _(' (started at %s)') % opts['rev']
2668 ui.warn((msg + '\n') % headless)
2668 ui.warn((msg + '\n') % headless)
2669
2669
2670 if not heads:
2670 if not heads:
2671 return 1
2671 return 1
2672
2672
2673 ui.pager('heads')
2673 ui.pager('heads')
2674 heads = sorted(heads, key=lambda x: -x.rev())
2674 heads = sorted(heads, key=lambda x: -x.rev())
2675 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
2675 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
2676 for ctx in heads:
2676 for ctx in heads:
2677 displayer.show(ctx)
2677 displayer.show(ctx)
2678 displayer.close()
2678 displayer.close()
2679
2679
2680 @command('help',
2680 @command('help',
2681 [('e', 'extension', None, _('show only help for extensions')),
2681 [('e', 'extension', None, _('show only help for extensions')),
2682 ('c', 'command', None, _('show only help for commands')),
2682 ('c', 'command', None, _('show only help for commands')),
2683 ('k', 'keyword', None, _('show topics matching keyword')),
2683 ('k', 'keyword', None, _('show topics matching keyword')),
2684 ('s', 'system', [], _('show help for specific platform(s)')),
2684 ('s', 'system', [], _('show help for specific platform(s)')),
2685 ],
2685 ],
2686 _('[-ecks] [TOPIC]'),
2686 _('[-ecks] [TOPIC]'),
2687 norepo=True, cmdtype=readonly)
2687 norepo=True, cmdtype=readonly)
2688 def help_(ui, name=None, **opts):
2688 def help_(ui, name=None, **opts):
2689 """show help for a given topic or a help overview
2689 """show help for a given topic or a help overview
2690
2690
2691 With no arguments, print a list of commands with short help messages.
2691 With no arguments, print a list of commands with short help messages.
2692
2692
2693 Given a topic, extension, or command name, print help for that
2693 Given a topic, extension, or command name, print help for that
2694 topic.
2694 topic.
2695
2695
2696 Returns 0 if successful.
2696 Returns 0 if successful.
2697 """
2697 """
2698
2698
2699 keep = opts.get(r'system') or []
2699 keep = opts.get(r'system') or []
2700 if len(keep) == 0:
2700 if len(keep) == 0:
2701 if pycompat.sysplatform.startswith('win'):
2701 if pycompat.sysplatform.startswith('win'):
2702 keep.append('windows')
2702 keep.append('windows')
2703 elif pycompat.sysplatform == 'OpenVMS':
2703 elif pycompat.sysplatform == 'OpenVMS':
2704 keep.append('vms')
2704 keep.append('vms')
2705 elif pycompat.sysplatform == 'plan9':
2705 elif pycompat.sysplatform == 'plan9':
2706 keep.append('plan9')
2706 keep.append('plan9')
2707 else:
2707 else:
2708 keep.append('unix')
2708 keep.append('unix')
2709 keep.append(pycompat.sysplatform.lower())
2709 keep.append(pycompat.sysplatform.lower())
2710 if ui.verbose:
2710 if ui.verbose:
2711 keep.append('verbose')
2711 keep.append('verbose')
2712
2712
2713 commands = sys.modules[__name__]
2713 commands = sys.modules[__name__]
2714 formatted = help.formattedhelp(ui, commands, name, keep=keep, **opts)
2714 formatted = help.formattedhelp(ui, commands, name, keep=keep, **opts)
2715 ui.pager('help')
2715 ui.pager('help')
2716 ui.write(formatted)
2716 ui.write(formatted)
2717
2717
2718
2718
2719 @command('identify|id',
2719 @command('identify|id',
2720 [('r', 'rev', '',
2720 [('r', 'rev', '',
2721 _('identify the specified revision'), _('REV')),
2721 _('identify the specified revision'), _('REV')),
2722 ('n', 'num', None, _('show local revision number')),
2722 ('n', 'num', None, _('show local revision number')),
2723 ('i', 'id', None, _('show global revision id')),
2723 ('i', 'id', None, _('show global revision id')),
2724 ('b', 'branch', None, _('show branch')),
2724 ('b', 'branch', None, _('show branch')),
2725 ('t', 'tags', None, _('show tags')),
2725 ('t', 'tags', None, _('show tags')),
2726 ('B', 'bookmarks', None, _('show bookmarks')),
2726 ('B', 'bookmarks', None, _('show bookmarks')),
2727 ] + remoteopts + formatteropts,
2727 ] + remoteopts + formatteropts,
2728 _('[-nibtB] [-r REV] [SOURCE]'),
2728 _('[-nibtB] [-r REV] [SOURCE]'),
2729 optionalrepo=True, cmdtype=readonly)
2729 optionalrepo=True, cmdtype=readonly)
2730 def identify(ui, repo, source=None, rev=None,
2730 def identify(ui, repo, source=None, rev=None,
2731 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
2731 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
2732 """identify the working directory or specified revision
2732 """identify the working directory or specified revision
2733
2733
2734 Print a summary identifying the repository state at REV using one or
2734 Print a summary identifying the repository state at REV using one or
2735 two parent hash identifiers, followed by a "+" if the working
2735 two parent hash identifiers, followed by a "+" if the working
2736 directory has uncommitted changes, the branch name (if not default),
2736 directory has uncommitted changes, the branch name (if not default),
2737 a list of tags, and a list of bookmarks.
2737 a list of tags, and a list of bookmarks.
2738
2738
2739 When REV is not given, print a summary of the current state of the
2739 When REV is not given, print a summary of the current state of the
2740 repository including the working directory. Specify -r. to get information
2740 repository including the working directory. Specify -r. to get information
2741 of the working directory parent without scanning uncommitted changes.
2741 of the working directory parent without scanning uncommitted changes.
2742
2742
2743 Specifying a path to a repository root or Mercurial bundle will
2743 Specifying a path to a repository root or Mercurial bundle will
2744 cause lookup to operate on that repository/bundle.
2744 cause lookup to operate on that repository/bundle.
2745
2745
2746 .. container:: verbose
2746 .. container:: verbose
2747
2747
2748 Examples:
2748 Examples:
2749
2749
2750 - generate a build identifier for the working directory::
2750 - generate a build identifier for the working directory::
2751
2751
2752 hg id --id > build-id.dat
2752 hg id --id > build-id.dat
2753
2753
2754 - find the revision corresponding to a tag::
2754 - find the revision corresponding to a tag::
2755
2755
2756 hg id -n -r 1.3
2756 hg id -n -r 1.3
2757
2757
2758 - check the most recent revision of a remote repository::
2758 - check the most recent revision of a remote repository::
2759
2759
2760 hg id -r tip https://www.mercurial-scm.org/repo/hg/
2760 hg id -r tip https://www.mercurial-scm.org/repo/hg/
2761
2761
2762 See :hg:`log` for generating more information about specific revisions,
2762 See :hg:`log` for generating more information about specific revisions,
2763 including full hash identifiers.
2763 including full hash identifiers.
2764
2764
2765 Returns 0 if successful.
2765 Returns 0 if successful.
2766 """
2766 """
2767
2767
2768 opts = pycompat.byteskwargs(opts)
2768 opts = pycompat.byteskwargs(opts)
2769 if not repo and not source:
2769 if not repo and not source:
2770 raise error.Abort(_("there is no Mercurial repository here "
2770 raise error.Abort(_("there is no Mercurial repository here "
2771 "(.hg not found)"))
2771 "(.hg not found)"))
2772
2772
2773 if ui.debugflag:
2773 if ui.debugflag:
2774 hexfunc = hex
2774 hexfunc = hex
2775 else:
2775 else:
2776 hexfunc = short
2776 hexfunc = short
2777 default = not (num or id or branch or tags or bookmarks)
2777 default = not (num or id or branch or tags or bookmarks)
2778 output = []
2778 output = []
2779 revs = []
2779 revs = []
2780
2780
2781 if source:
2781 if source:
2782 source, branches = hg.parseurl(ui.expandpath(source))
2782 source, branches = hg.parseurl(ui.expandpath(source))
2783 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
2783 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
2784 repo = peer.local()
2784 repo = peer.local()
2785 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
2785 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
2786
2786
2787 fm = ui.formatter('identify', opts)
2787 fm = ui.formatter('identify', opts)
2788 fm.startitem()
2788 fm.startitem()
2789
2789
2790 if not repo:
2790 if not repo:
2791 if num or branch or tags:
2791 if num or branch or tags:
2792 raise error.Abort(
2792 raise error.Abort(
2793 _("can't query remote revision number, branch, or tags"))
2793 _("can't query remote revision number, branch, or tags"))
2794 if not rev and revs:
2794 if not rev and revs:
2795 rev = revs[0]
2795 rev = revs[0]
2796 if not rev:
2796 if not rev:
2797 rev = "tip"
2797 rev = "tip"
2798
2798
2799 remoterev = peer.lookup(rev)
2799 remoterev = peer.lookup(rev)
2800 hexrev = hexfunc(remoterev)
2800 hexrev = hexfunc(remoterev)
2801 if default or id:
2801 if default or id:
2802 output = [hexrev]
2802 output = [hexrev]
2803 fm.data(id=hexrev)
2803 fm.data(id=hexrev)
2804
2804
2805 def getbms():
2805 def getbms():
2806 bms = []
2806 bms = []
2807
2807
2808 if 'bookmarks' in peer.listkeys('namespaces'):
2808 if 'bookmarks' in peer.listkeys('namespaces'):
2809 hexremoterev = hex(remoterev)
2809 hexremoterev = hex(remoterev)
2810 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
2810 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
2811 if bmr == hexremoterev]
2811 if bmr == hexremoterev]
2812
2812
2813 return sorted(bms)
2813 return sorted(bms)
2814
2814
2815 bms = getbms()
2815 bms = getbms()
2816 if bookmarks:
2816 if bookmarks:
2817 output.extend(bms)
2817 output.extend(bms)
2818 elif default and not ui.quiet:
2818 elif default and not ui.quiet:
2819 # multiple bookmarks for a single parent separated by '/'
2819 # multiple bookmarks for a single parent separated by '/'
2820 bm = '/'.join(bms)
2820 bm = '/'.join(bms)
2821 if bm:
2821 if bm:
2822 output.append(bm)
2822 output.append(bm)
2823
2823
2824 fm.data(node=hex(remoterev))
2824 fm.data(node=hex(remoterev))
2825 fm.data(bookmarks=fm.formatlist(bms, name='bookmark'))
2825 fm.data(bookmarks=fm.formatlist(bms, name='bookmark'))
2826 else:
2826 else:
2827 if rev:
2827 if rev:
2828 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
2828 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
2829 ctx = scmutil.revsingle(repo, rev, None)
2829 ctx = scmutil.revsingle(repo, rev, None)
2830
2830
2831 if ctx.rev() is None:
2831 if ctx.rev() is None:
2832 ctx = repo[None]
2832 ctx = repo[None]
2833 parents = ctx.parents()
2833 parents = ctx.parents()
2834 taglist = []
2834 taglist = []
2835 for p in parents:
2835 for p in parents:
2836 taglist.extend(p.tags())
2836 taglist.extend(p.tags())
2837
2837
2838 dirty = ""
2838 dirty = ""
2839 if ctx.dirty(missing=True, merge=False, branch=False):
2839 if ctx.dirty(missing=True, merge=False, branch=False):
2840 dirty = '+'
2840 dirty = '+'
2841 fm.data(dirty=dirty)
2841 fm.data(dirty=dirty)
2842
2842
2843 hexoutput = [hexfunc(p.node()) for p in parents]
2843 hexoutput = [hexfunc(p.node()) for p in parents]
2844 if default or id:
2844 if default or id:
2845 output = ["%s%s" % ('+'.join(hexoutput), dirty)]
2845 output = ["%s%s" % ('+'.join(hexoutput), dirty)]
2846 fm.data(id="%s%s" % ('+'.join(hexoutput), dirty))
2846 fm.data(id="%s%s" % ('+'.join(hexoutput), dirty))
2847
2847
2848 if num:
2848 if num:
2849 numoutput = ["%d" % p.rev() for p in parents]
2849 numoutput = ["%d" % p.rev() for p in parents]
2850 output.append("%s%s" % ('+'.join(numoutput), dirty))
2850 output.append("%s%s" % ('+'.join(numoutput), dirty))
2851
2851
2852 fn = fm.nested('parents')
2852 fn = fm.nested('parents')
2853 for p in parents:
2853 for p in parents:
2854 fn.startitem()
2854 fn.startitem()
2855 fn.data(rev=p.rev())
2855 fn.data(rev=p.rev())
2856 fn.data(node=p.hex())
2856 fn.data(node=p.hex())
2857 fn.context(ctx=p)
2857 fn.context(ctx=p)
2858 fn.end()
2858 fn.end()
2859 else:
2859 else:
2860 hexoutput = hexfunc(ctx.node())
2860 hexoutput = hexfunc(ctx.node())
2861 if default or id:
2861 if default or id:
2862 output = [hexoutput]
2862 output = [hexoutput]
2863 fm.data(id=hexoutput)
2863 fm.data(id=hexoutput)
2864
2864
2865 if num:
2865 if num:
2866 output.append(pycompat.bytestr(ctx.rev()))
2866 output.append(pycompat.bytestr(ctx.rev()))
2867 taglist = ctx.tags()
2867 taglist = ctx.tags()
2868
2868
2869 if default and not ui.quiet:
2869 if default and not ui.quiet:
2870 b = ctx.branch()
2870 b = ctx.branch()
2871 if b != 'default':
2871 if b != 'default':
2872 output.append("(%s)" % b)
2872 output.append("(%s)" % b)
2873
2873
2874 # multiple tags for a single parent separated by '/'
2874 # multiple tags for a single parent separated by '/'
2875 t = '/'.join(taglist)
2875 t = '/'.join(taglist)
2876 if t:
2876 if t:
2877 output.append(t)
2877 output.append(t)
2878
2878
2879 # multiple bookmarks for a single parent separated by '/'
2879 # multiple bookmarks for a single parent separated by '/'
2880 bm = '/'.join(ctx.bookmarks())
2880 bm = '/'.join(ctx.bookmarks())
2881 if bm:
2881 if bm:
2882 output.append(bm)
2882 output.append(bm)
2883 else:
2883 else:
2884 if branch:
2884 if branch:
2885 output.append(ctx.branch())
2885 output.append(ctx.branch())
2886
2886
2887 if tags:
2887 if tags:
2888 output.extend(taglist)
2888 output.extend(taglist)
2889
2889
2890 if bookmarks:
2890 if bookmarks:
2891 output.extend(ctx.bookmarks())
2891 output.extend(ctx.bookmarks())
2892
2892
2893 fm.data(node=ctx.hex())
2893 fm.data(node=ctx.hex())
2894 fm.data(branch=ctx.branch())
2894 fm.data(branch=ctx.branch())
2895 fm.data(tags=fm.formatlist(taglist, name='tag', sep=':'))
2895 fm.data(tags=fm.formatlist(taglist, name='tag', sep=':'))
2896 fm.data(bookmarks=fm.formatlist(ctx.bookmarks(), name='bookmark'))
2896 fm.data(bookmarks=fm.formatlist(ctx.bookmarks(), name='bookmark'))
2897 fm.context(ctx=ctx)
2897 fm.context(ctx=ctx)
2898
2898
2899 fm.plain("%s\n" % ' '.join(output))
2899 fm.plain("%s\n" % ' '.join(output))
2900 fm.end()
2900 fm.end()
2901
2901
2902 @command('import|patch',
2902 @command('import|patch',
2903 [('p', 'strip', 1,
2903 [('p', 'strip', 1,
2904 _('directory strip option for patch. This has the same '
2904 _('directory strip option for patch. This has the same '
2905 'meaning as the corresponding patch option'), _('NUM')),
2905 'meaning as the corresponding patch option'), _('NUM')),
2906 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
2906 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
2907 ('e', 'edit', False, _('invoke editor on commit messages')),
2907 ('e', 'edit', False, _('invoke editor on commit messages')),
2908 ('f', 'force', None,
2908 ('f', 'force', None,
2909 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
2909 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
2910 ('', 'no-commit', None,
2910 ('', 'no-commit', None,
2911 _("don't commit, just update the working directory")),
2911 _("don't commit, just update the working directory")),
2912 ('', 'bypass', None,
2912 ('', 'bypass', None,
2913 _("apply patch without touching the working directory")),
2913 _("apply patch without touching the working directory")),
2914 ('', 'partial', None,
2914 ('', 'partial', None,
2915 _('commit even if some hunks fail')),
2915 _('commit even if some hunks fail')),
2916 ('', 'exact', None,
2916 ('', 'exact', None,
2917 _('abort if patch would apply lossily')),
2917 _('abort if patch would apply lossily')),
2918 ('', 'prefix', '',
2918 ('', 'prefix', '',
2919 _('apply patch to subdirectory'), _('DIR')),
2919 _('apply patch to subdirectory'), _('DIR')),
2920 ('', 'import-branch', None,
2920 ('', 'import-branch', None,
2921 _('use any branch information in patch (implied by --exact)'))] +
2921 _('use any branch information in patch (implied by --exact)'))] +
2922 commitopts + commitopts2 + similarityopts,
2922 commitopts + commitopts2 + similarityopts,
2923 _('[OPTION]... PATCH...'))
2923 _('[OPTION]... PATCH...'))
2924 def import_(ui, repo, patch1=None, *patches, **opts):
2924 def import_(ui, repo, patch1=None, *patches, **opts):
2925 """import an ordered set of patches
2925 """import an ordered set of patches
2926
2926
2927 Import a list of patches and commit them individually (unless
2927 Import a list of patches and commit them individually (unless
2928 --no-commit is specified).
2928 --no-commit is specified).
2929
2929
2930 To read a patch from standard input (stdin), use "-" as the patch
2930 To read a patch from standard input (stdin), use "-" as the patch
2931 name. If a URL is specified, the patch will be downloaded from
2931 name. If a URL is specified, the patch will be downloaded from
2932 there.
2932 there.
2933
2933
2934 Import first applies changes to the working directory (unless
2934 Import first applies changes to the working directory (unless
2935 --bypass is specified), import will abort if there are outstanding
2935 --bypass is specified), import will abort if there are outstanding
2936 changes.
2936 changes.
2937
2937
2938 Use --bypass to apply and commit patches directly to the
2938 Use --bypass to apply and commit patches directly to the
2939 repository, without affecting the working directory. Without
2939 repository, without affecting the working directory. Without
2940 --exact, patches will be applied on top of the working directory
2940 --exact, patches will be applied on top of the working directory
2941 parent revision.
2941 parent revision.
2942
2942
2943 You can import a patch straight from a mail message. Even patches
2943 You can import a patch straight from a mail message. Even patches
2944 as attachments work (to use the body part, it must have type
2944 as attachments work (to use the body part, it must have type
2945 text/plain or text/x-patch). From and Subject headers of email
2945 text/plain or text/x-patch). From and Subject headers of email
2946 message are used as default committer and commit message. All
2946 message are used as default committer and commit message. All
2947 text/plain body parts before first diff are added to the commit
2947 text/plain body parts before first diff are added to the commit
2948 message.
2948 message.
2949
2949
2950 If the imported patch was generated by :hg:`export`, user and
2950 If the imported patch was generated by :hg:`export`, user and
2951 description from patch override values from message headers and
2951 description from patch override values from message headers and
2952 body. Values given on command line with -m/--message and -u/--user
2952 body. Values given on command line with -m/--message and -u/--user
2953 override these.
2953 override these.
2954
2954
2955 If --exact is specified, import will set the working directory to
2955 If --exact is specified, import will set the working directory to
2956 the parent of each patch before applying it, and will abort if the
2956 the parent of each patch before applying it, and will abort if the
2957 resulting changeset has a different ID than the one recorded in
2957 resulting changeset has a different ID than the one recorded in
2958 the patch. This will guard against various ways that portable
2958 the patch. This will guard against various ways that portable
2959 patch formats and mail systems might fail to transfer Mercurial
2959 patch formats and mail systems might fail to transfer Mercurial
2960 data or metadata. See :hg:`bundle` for lossless transmission.
2960 data or metadata. See :hg:`bundle` for lossless transmission.
2961
2961
2962 Use --partial to ensure a changeset will be created from the patch
2962 Use --partial to ensure a changeset will be created from the patch
2963 even if some hunks fail to apply. Hunks that fail to apply will be
2963 even if some hunks fail to apply. Hunks that fail to apply will be
2964 written to a <target-file>.rej file. Conflicts can then be resolved
2964 written to a <target-file>.rej file. Conflicts can then be resolved
2965 by hand before :hg:`commit --amend` is run to update the created
2965 by hand before :hg:`commit --amend` is run to update the created
2966 changeset. This flag exists to let people import patches that
2966 changeset. This flag exists to let people import patches that
2967 partially apply without losing the associated metadata (author,
2967 partially apply without losing the associated metadata (author,
2968 date, description, ...).
2968 date, description, ...).
2969
2969
2970 .. note::
2970 .. note::
2971
2971
2972 When no hunks apply cleanly, :hg:`import --partial` will create
2972 When no hunks apply cleanly, :hg:`import --partial` will create
2973 an empty changeset, importing only the patch metadata.
2973 an empty changeset, importing only the patch metadata.
2974
2974
2975 With -s/--similarity, hg will attempt to discover renames and
2975 With -s/--similarity, hg will attempt to discover renames and
2976 copies in the patch in the same way as :hg:`addremove`.
2976 copies in the patch in the same way as :hg:`addremove`.
2977
2977
2978 It is possible to use external patch programs to perform the patch
2978 It is possible to use external patch programs to perform the patch
2979 by setting the ``ui.patch`` configuration option. For the default
2979 by setting the ``ui.patch`` configuration option. For the default
2980 internal tool, the fuzz can also be configured via ``patch.fuzz``.
2980 internal tool, the fuzz can also be configured via ``patch.fuzz``.
2981 See :hg:`help config` for more information about configuration
2981 See :hg:`help config` for more information about configuration
2982 files and how to use these options.
2982 files and how to use these options.
2983
2983
2984 See :hg:`help dates` for a list of formats valid for -d/--date.
2984 See :hg:`help dates` for a list of formats valid for -d/--date.
2985
2985
2986 .. container:: verbose
2986 .. container:: verbose
2987
2987
2988 Examples:
2988 Examples:
2989
2989
2990 - import a traditional patch from a website and detect renames::
2990 - import a traditional patch from a website and detect renames::
2991
2991
2992 hg import -s 80 http://example.com/bugfix.patch
2992 hg import -s 80 http://example.com/bugfix.patch
2993
2993
2994 - import a changeset from an hgweb server::
2994 - import a changeset from an hgweb server::
2995
2995
2996 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
2996 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
2997
2997
2998 - import all the patches in an Unix-style mbox::
2998 - import all the patches in an Unix-style mbox::
2999
2999
3000 hg import incoming-patches.mbox
3000 hg import incoming-patches.mbox
3001
3001
3002 - import patches from stdin::
3002 - import patches from stdin::
3003
3003
3004 hg import -
3004 hg import -
3005
3005
3006 - attempt to exactly restore an exported changeset (not always
3006 - attempt to exactly restore an exported changeset (not always
3007 possible)::
3007 possible)::
3008
3008
3009 hg import --exact proposed-fix.patch
3009 hg import --exact proposed-fix.patch
3010
3010
3011 - use an external tool to apply a patch which is too fuzzy for
3011 - use an external tool to apply a patch which is too fuzzy for
3012 the default internal tool.
3012 the default internal tool.
3013
3013
3014 hg import --config ui.patch="patch --merge" fuzzy.patch
3014 hg import --config ui.patch="patch --merge" fuzzy.patch
3015
3015
3016 - change the default fuzzing from 2 to a less strict 7
3016 - change the default fuzzing from 2 to a less strict 7
3017
3017
3018 hg import --config ui.fuzz=7 fuzz.patch
3018 hg import --config ui.fuzz=7 fuzz.patch
3019
3019
3020 Returns 0 on success, 1 on partial success (see --partial).
3020 Returns 0 on success, 1 on partial success (see --partial).
3021 """
3021 """
3022
3022
3023 opts = pycompat.byteskwargs(opts)
3023 opts = pycompat.byteskwargs(opts)
3024 if not patch1:
3024 if not patch1:
3025 raise error.Abort(_('need at least one patch to import'))
3025 raise error.Abort(_('need at least one patch to import'))
3026
3026
3027 patches = (patch1,) + patches
3027 patches = (patch1,) + patches
3028
3028
3029 date = opts.get('date')
3029 date = opts.get('date')
3030 if date:
3030 if date:
3031 opts['date'] = dateutil.parsedate(date)
3031 opts['date'] = dateutil.parsedate(date)
3032
3032
3033 exact = opts.get('exact')
3033 exact = opts.get('exact')
3034 update = not opts.get('bypass')
3034 update = not opts.get('bypass')
3035 if not update and opts.get('no_commit'):
3035 if not update and opts.get('no_commit'):
3036 raise error.Abort(_('cannot use --no-commit with --bypass'))
3036 raise error.Abort(_('cannot use --no-commit with --bypass'))
3037 try:
3037 try:
3038 sim = float(opts.get('similarity') or 0)
3038 sim = float(opts.get('similarity') or 0)
3039 except ValueError:
3039 except ValueError:
3040 raise error.Abort(_('similarity must be a number'))
3040 raise error.Abort(_('similarity must be a number'))
3041 if sim < 0 or sim > 100:
3041 if sim < 0 or sim > 100:
3042 raise error.Abort(_('similarity must be between 0 and 100'))
3042 raise error.Abort(_('similarity must be between 0 and 100'))
3043 if sim and not update:
3043 if sim and not update:
3044 raise error.Abort(_('cannot use --similarity with --bypass'))
3044 raise error.Abort(_('cannot use --similarity with --bypass'))
3045 if exact:
3045 if exact:
3046 if opts.get('edit'):
3046 if opts.get('edit'):
3047 raise error.Abort(_('cannot use --exact with --edit'))
3047 raise error.Abort(_('cannot use --exact with --edit'))
3048 if opts.get('prefix'):
3048 if opts.get('prefix'):
3049 raise error.Abort(_('cannot use --exact with --prefix'))
3049 raise error.Abort(_('cannot use --exact with --prefix'))
3050
3050
3051 base = opts["base"]
3051 base = opts["base"]
3052 wlock = dsguard = lock = tr = None
3052 wlock = dsguard = lock = tr = None
3053 msgs = []
3053 msgs = []
3054 ret = 0
3054 ret = 0
3055
3055
3056
3056
3057 try:
3057 try:
3058 wlock = repo.wlock()
3058 wlock = repo.wlock()
3059
3059
3060 if update:
3060 if update:
3061 cmdutil.checkunfinished(repo)
3061 cmdutil.checkunfinished(repo)
3062 if (exact or not opts.get('force')):
3062 if (exact or not opts.get('force')):
3063 cmdutil.bailifchanged(repo)
3063 cmdutil.bailifchanged(repo)
3064
3064
3065 if not opts.get('no_commit'):
3065 if not opts.get('no_commit'):
3066 lock = repo.lock()
3066 lock = repo.lock()
3067 tr = repo.transaction('import')
3067 tr = repo.transaction('import')
3068 else:
3068 else:
3069 dsguard = dirstateguard.dirstateguard(repo, 'import')
3069 dsguard = dirstateguard.dirstateguard(repo, 'import')
3070 parents = repo[None].parents()
3070 parents = repo[None].parents()
3071 for patchurl in patches:
3071 for patchurl in patches:
3072 if patchurl == '-':
3072 if patchurl == '-':
3073 ui.status(_('applying patch from stdin\n'))
3073 ui.status(_('applying patch from stdin\n'))
3074 patchfile = ui.fin
3074 patchfile = ui.fin
3075 patchurl = 'stdin' # for error message
3075 patchurl = 'stdin' # for error message
3076 else:
3076 else:
3077 patchurl = os.path.join(base, patchurl)
3077 patchurl = os.path.join(base, patchurl)
3078 ui.status(_('applying %s\n') % patchurl)
3078 ui.status(_('applying %s\n') % patchurl)
3079 patchfile = hg.openpath(ui, patchurl)
3079 patchfile = hg.openpath(ui, patchurl)
3080
3080
3081 haspatch = False
3081 haspatch = False
3082 for hunk in patch.split(patchfile):
3082 for hunk in patch.split(patchfile):
3083 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
3083 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
3084 parents, opts,
3084 parents, opts,
3085 msgs, hg.clean)
3085 msgs, hg.clean)
3086 if msg:
3086 if msg:
3087 haspatch = True
3087 haspatch = True
3088 ui.note(msg + '\n')
3088 ui.note(msg + '\n')
3089 if update or exact:
3089 if update or exact:
3090 parents = repo[None].parents()
3090 parents = repo[None].parents()
3091 else:
3091 else:
3092 parents = [repo[node]]
3092 parents = [repo[node]]
3093 if rej:
3093 if rej:
3094 ui.write_err(_("patch applied partially\n"))
3094 ui.write_err(_("patch applied partially\n"))
3095 ui.write_err(_("(fix the .rej files and run "
3095 ui.write_err(_("(fix the .rej files and run "
3096 "`hg commit --amend`)\n"))
3096 "`hg commit --amend`)\n"))
3097 ret = 1
3097 ret = 1
3098 break
3098 break
3099
3099
3100 if not haspatch:
3100 if not haspatch:
3101 raise error.Abort(_('%s: no diffs found') % patchurl)
3101 raise error.Abort(_('%s: no diffs found') % patchurl)
3102
3102
3103 if tr:
3103 if tr:
3104 tr.close()
3104 tr.close()
3105 if msgs:
3105 if msgs:
3106 repo.savecommitmessage('\n* * *\n'.join(msgs))
3106 repo.savecommitmessage('\n* * *\n'.join(msgs))
3107 if dsguard:
3107 if dsguard:
3108 dsguard.close()
3108 dsguard.close()
3109 return ret
3109 return ret
3110 finally:
3110 finally:
3111 if tr:
3111 if tr:
3112 tr.release()
3112 tr.release()
3113 release(lock, dsguard, wlock)
3113 release(lock, dsguard, wlock)
3114
3114
3115 @command('incoming|in',
3115 @command('incoming|in',
3116 [('f', 'force', None,
3116 [('f', 'force', None,
3117 _('run even if remote repository is unrelated')),
3117 _('run even if remote repository is unrelated')),
3118 ('n', 'newest-first', None, _('show newest record first')),
3118 ('n', 'newest-first', None, _('show newest record first')),
3119 ('', 'bundle', '',
3119 ('', 'bundle', '',
3120 _('file to store the bundles into'), _('FILE')),
3120 _('file to store the bundles into'), _('FILE')),
3121 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3121 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3122 ('B', 'bookmarks', False, _("compare bookmarks")),
3122 ('B', 'bookmarks', False, _("compare bookmarks")),
3123 ('b', 'branch', [],
3123 ('b', 'branch', [],
3124 _('a specific branch you would like to pull'), _('BRANCH')),
3124 _('a specific branch you would like to pull'), _('BRANCH')),
3125 ] + logopts + remoteopts + subrepoopts,
3125 ] + logopts + remoteopts + subrepoopts,
3126 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3126 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3127 def incoming(ui, repo, source="default", **opts):
3127 def incoming(ui, repo, source="default", **opts):
3128 """show new changesets found in source
3128 """show new changesets found in source
3129
3129
3130 Show new changesets found in the specified path/URL or the default
3130 Show new changesets found in the specified path/URL or the default
3131 pull location. These are the changesets that would have been pulled
3131 pull location. These are the changesets that would have been pulled
3132 by :hg:`pull` at the time you issued this command.
3132 by :hg:`pull` at the time you issued this command.
3133
3133
3134 See pull for valid source format details.
3134 See pull for valid source format details.
3135
3135
3136 .. container:: verbose
3136 .. container:: verbose
3137
3137
3138 With -B/--bookmarks, the result of bookmark comparison between
3138 With -B/--bookmarks, the result of bookmark comparison between
3139 local and remote repositories is displayed. With -v/--verbose,
3139 local and remote repositories is displayed. With -v/--verbose,
3140 status is also displayed for each bookmark like below::
3140 status is also displayed for each bookmark like below::
3141
3141
3142 BM1 01234567890a added
3142 BM1 01234567890a added
3143 BM2 1234567890ab advanced
3143 BM2 1234567890ab advanced
3144 BM3 234567890abc diverged
3144 BM3 234567890abc diverged
3145 BM4 34567890abcd changed
3145 BM4 34567890abcd changed
3146
3146
3147 The action taken locally when pulling depends on the
3147 The action taken locally when pulling depends on the
3148 status of each bookmark:
3148 status of each bookmark:
3149
3149
3150 :``added``: pull will create it
3150 :``added``: pull will create it
3151 :``advanced``: pull will update it
3151 :``advanced``: pull will update it
3152 :``diverged``: pull will create a divergent bookmark
3152 :``diverged``: pull will create a divergent bookmark
3153 :``changed``: result depends on remote changesets
3153 :``changed``: result depends on remote changesets
3154
3154
3155 From the point of view of pulling behavior, bookmark
3155 From the point of view of pulling behavior, bookmark
3156 existing only in the remote repository are treated as ``added``,
3156 existing only in the remote repository are treated as ``added``,
3157 even if it is in fact locally deleted.
3157 even if it is in fact locally deleted.
3158
3158
3159 .. container:: verbose
3159 .. container:: verbose
3160
3160
3161 For remote repository, using --bundle avoids downloading the
3161 For remote repository, using --bundle avoids downloading the
3162 changesets twice if the incoming is followed by a pull.
3162 changesets twice if the incoming is followed by a pull.
3163
3163
3164 Examples:
3164 Examples:
3165
3165
3166 - show incoming changes with patches and full description::
3166 - show incoming changes with patches and full description::
3167
3167
3168 hg incoming -vp
3168 hg incoming -vp
3169
3169
3170 - show incoming changes excluding merges, store a bundle::
3170 - show incoming changes excluding merges, store a bundle::
3171
3171
3172 hg in -vpM --bundle incoming.hg
3172 hg in -vpM --bundle incoming.hg
3173 hg pull incoming.hg
3173 hg pull incoming.hg
3174
3174
3175 - briefly list changes inside a bundle::
3175 - briefly list changes inside a bundle::
3176
3176
3177 hg in changes.hg -T "{desc|firstline}\\n"
3177 hg in changes.hg -T "{desc|firstline}\\n"
3178
3178
3179 Returns 0 if there are incoming changes, 1 otherwise.
3179 Returns 0 if there are incoming changes, 1 otherwise.
3180 """
3180 """
3181 opts = pycompat.byteskwargs(opts)
3181 opts = pycompat.byteskwargs(opts)
3182 if opts.get('graph'):
3182 if opts.get('graph'):
3183 logcmdutil.checkunsupportedgraphflags([], opts)
3183 logcmdutil.checkunsupportedgraphflags([], opts)
3184 def display(other, chlist, displayer):
3184 def display(other, chlist, displayer):
3185 revdag = logcmdutil.graphrevs(other, chlist, opts)
3185 revdag = logcmdutil.graphrevs(other, chlist, opts)
3186 logcmdutil.displaygraph(ui, repo, revdag, displayer,
3186 logcmdutil.displaygraph(ui, repo, revdag, displayer,
3187 graphmod.asciiedges)
3187 graphmod.asciiedges)
3188
3188
3189 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3189 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3190 return 0
3190 return 0
3191
3191
3192 if opts.get('bundle') and opts.get('subrepos'):
3192 if opts.get('bundle') and opts.get('subrepos'):
3193 raise error.Abort(_('cannot combine --bundle and --subrepos'))
3193 raise error.Abort(_('cannot combine --bundle and --subrepos'))
3194
3194
3195 if opts.get('bookmarks'):
3195 if opts.get('bookmarks'):
3196 source, branches = hg.parseurl(ui.expandpath(source),
3196 source, branches = hg.parseurl(ui.expandpath(source),
3197 opts.get('branch'))
3197 opts.get('branch'))
3198 other = hg.peer(repo, opts, source)
3198 other = hg.peer(repo, opts, source)
3199 if 'bookmarks' not in other.listkeys('namespaces'):
3199 if 'bookmarks' not in other.listkeys('namespaces'):
3200 ui.warn(_("remote doesn't support bookmarks\n"))
3200 ui.warn(_("remote doesn't support bookmarks\n"))
3201 return 0
3201 return 0
3202 ui.pager('incoming')
3202 ui.pager('incoming')
3203 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3203 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3204 return bookmarks.incoming(ui, repo, other)
3204 return bookmarks.incoming(ui, repo, other)
3205
3205
3206 repo._subtoppath = ui.expandpath(source)
3206 repo._subtoppath = ui.expandpath(source)
3207 try:
3207 try:
3208 return hg.incoming(ui, repo, source, opts)
3208 return hg.incoming(ui, repo, source, opts)
3209 finally:
3209 finally:
3210 del repo._subtoppath
3210 del repo._subtoppath
3211
3211
3212
3212
3213 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
3213 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
3214 norepo=True)
3214 norepo=True)
3215 def init(ui, dest=".", **opts):
3215 def init(ui, dest=".", **opts):
3216 """create a new repository in the given directory
3216 """create a new repository in the given directory
3217
3217
3218 Initialize a new repository in the given directory. If the given
3218 Initialize a new repository in the given directory. If the given
3219 directory does not exist, it will be created.
3219 directory does not exist, it will be created.
3220
3220
3221 If no directory is given, the current directory is used.
3221 If no directory is given, the current directory is used.
3222
3222
3223 It is possible to specify an ``ssh://`` URL as the destination.
3223 It is possible to specify an ``ssh://`` URL as the destination.
3224 See :hg:`help urls` for more information.
3224 See :hg:`help urls` for more information.
3225
3225
3226 Returns 0 on success.
3226 Returns 0 on success.
3227 """
3227 """
3228 opts = pycompat.byteskwargs(opts)
3228 opts = pycompat.byteskwargs(opts)
3229 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3229 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3230
3230
3231 @command('locate',
3231 @command('locate',
3232 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3232 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3233 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3233 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3234 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3234 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3235 ] + walkopts,
3235 ] + walkopts,
3236 _('[OPTION]... [PATTERN]...'))
3236 _('[OPTION]... [PATTERN]...'))
3237 def locate(ui, repo, *pats, **opts):
3237 def locate(ui, repo, *pats, **opts):
3238 """locate files matching specific patterns (DEPRECATED)
3238 """locate files matching specific patterns (DEPRECATED)
3239
3239
3240 Print files under Mercurial control in the working directory whose
3240 Print files under Mercurial control in the working directory whose
3241 names match the given patterns.
3241 names match the given patterns.
3242
3242
3243 By default, this command searches all directories in the working
3243 By default, this command searches all directories in the working
3244 directory. To search just the current directory and its
3244 directory. To search just the current directory and its
3245 subdirectories, use "--include .".
3245 subdirectories, use "--include .".
3246
3246
3247 If no patterns are given to match, this command prints the names
3247 If no patterns are given to match, this command prints the names
3248 of all files under Mercurial control in the working directory.
3248 of all files under Mercurial control in the working directory.
3249
3249
3250 If you want to feed the output of this command into the "xargs"
3250 If you want to feed the output of this command into the "xargs"
3251 command, use the -0 option to both this command and "xargs". This
3251 command, use the -0 option to both this command and "xargs". This
3252 will avoid the problem of "xargs" treating single filenames that
3252 will avoid the problem of "xargs" treating single filenames that
3253 contain whitespace as multiple filenames.
3253 contain whitespace as multiple filenames.
3254
3254
3255 See :hg:`help files` for a more versatile command.
3255 See :hg:`help files` for a more versatile command.
3256
3256
3257 Returns 0 if a match is found, 1 otherwise.
3257 Returns 0 if a match is found, 1 otherwise.
3258 """
3258 """
3259 opts = pycompat.byteskwargs(opts)
3259 opts = pycompat.byteskwargs(opts)
3260 if opts.get('print0'):
3260 if opts.get('print0'):
3261 end = '\0'
3261 end = '\0'
3262 else:
3262 else:
3263 end = '\n'
3263 end = '\n'
3264 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3264 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3265
3265
3266 ret = 1
3266 ret = 1
3267 m = scmutil.match(ctx, pats, opts, default='relglob',
3267 m = scmutil.match(ctx, pats, opts, default='relglob',
3268 badfn=lambda x, y: False)
3268 badfn=lambda x, y: False)
3269
3269
3270 ui.pager('locate')
3270 ui.pager('locate')
3271 for abs in ctx.matches(m):
3271 for abs in ctx.matches(m):
3272 if opts.get('fullpath'):
3272 if opts.get('fullpath'):
3273 ui.write(repo.wjoin(abs), end)
3273 ui.write(repo.wjoin(abs), end)
3274 else:
3274 else:
3275 ui.write(((pats and m.rel(abs)) or abs), end)
3275 ui.write(((pats and m.rel(abs)) or abs), end)
3276 ret = 0
3276 ret = 0
3277
3277
3278 return ret
3278 return ret
3279
3279
3280 @command('^log|history',
3280 @command('^log|history',
3281 [('f', 'follow', None,
3281 [('f', 'follow', None,
3282 _('follow changeset history, or file history across copies and renames')),
3282 _('follow changeset history, or file history across copies and renames')),
3283 ('', 'follow-first', None,
3283 ('', 'follow-first', None,
3284 _('only follow the first parent of merge changesets (DEPRECATED)')),
3284 _('only follow the first parent of merge changesets (DEPRECATED)')),
3285 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3285 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3286 ('C', 'copies', None, _('show copied files')),
3286 ('C', 'copies', None, _('show copied files')),
3287 ('k', 'keyword', [],
3287 ('k', 'keyword', [],
3288 _('do case-insensitive search for a given text'), _('TEXT')),
3288 _('do case-insensitive search for a given text'), _('TEXT')),
3289 ('r', 'rev', [], _('show the specified revision or revset'), _('REV')),
3289 ('r', 'rev', [], _('show the specified revision or revset'), _('REV')),
3290 ('L', 'line-range', [],
3290 ('L', 'line-range', [],
3291 _('follow line range of specified file (EXPERIMENTAL)'),
3291 _('follow line range of specified file (EXPERIMENTAL)'),
3292 _('FILE,RANGE')),
3292 _('FILE,RANGE')),
3293 ('', 'removed', None, _('include revisions where files were removed')),
3293 ('', 'removed', None, _('include revisions where files were removed')),
3294 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3294 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3295 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3295 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3296 ('', 'only-branch', [],
3296 ('', 'only-branch', [],
3297 _('show only changesets within the given named branch (DEPRECATED)'),
3297 _('show only changesets within the given named branch (DEPRECATED)'),
3298 _('BRANCH')),
3298 _('BRANCH')),
3299 ('b', 'branch', [],
3299 ('b', 'branch', [],
3300 _('show changesets within the given named branch'), _('BRANCH')),
3300 _('show changesets within the given named branch'), _('BRANCH')),
3301 ('P', 'prune', [],
3301 ('P', 'prune', [],
3302 _('do not display revision or any of its ancestors'), _('REV')),
3302 _('do not display revision or any of its ancestors'), _('REV')),
3303 ] + logopts + walkopts,
3303 ] + logopts + walkopts,
3304 _('[OPTION]... [FILE]'),
3304 _('[OPTION]... [FILE]'),
3305 inferrepo=True, cmdtype=readonly)
3305 inferrepo=True, cmdtype=readonly)
3306 def log(ui, repo, *pats, **opts):
3306 def log(ui, repo, *pats, **opts):
3307 """show revision history of entire repository or files
3307 """show revision history of entire repository or files
3308
3308
3309 Print the revision history of the specified files or the entire
3309 Print the revision history of the specified files or the entire
3310 project.
3310 project.
3311
3311
3312 If no revision range is specified, the default is ``tip:0`` unless
3312 If no revision range is specified, the default is ``tip:0`` unless
3313 --follow is set, in which case the working directory parent is
3313 --follow is set, in which case the working directory parent is
3314 used as the starting revision.
3314 used as the starting revision.
3315
3315
3316 File history is shown without following rename or copy history of
3316 File history is shown without following rename or copy history of
3317 files. Use -f/--follow with a filename to follow history across
3317 files. Use -f/--follow with a filename to follow history across
3318 renames and copies. --follow without a filename will only show
3318 renames and copies. --follow without a filename will only show
3319 ancestors of the starting revision.
3319 ancestors of the starting revision.
3320
3320
3321 By default this command prints revision number and changeset id,
3321 By default this command prints revision number and changeset id,
3322 tags, non-trivial parents, user, date and time, and a summary for
3322 tags, non-trivial parents, user, date and time, and a summary for
3323 each commit. When the -v/--verbose switch is used, the list of
3323 each commit. When the -v/--verbose switch is used, the list of
3324 changed files and full commit message are shown.
3324 changed files and full commit message are shown.
3325
3325
3326 With --graph the revisions are shown as an ASCII art DAG with the most
3326 With --graph the revisions are shown as an ASCII art DAG with the most
3327 recent changeset at the top.
3327 recent changeset at the top.
3328 'o' is a changeset, '@' is a working directory parent, '_' closes a branch,
3328 'o' is a changeset, '@' is a working directory parent, '_' closes a branch,
3329 'x' is obsolete, '*' is unstable, and '+' represents a fork where the
3329 'x' is obsolete, '*' is unstable, and '+' represents a fork where the
3330 changeset from the lines below is a parent of the 'o' merge on the same
3330 changeset from the lines below is a parent of the 'o' merge on the same
3331 line.
3331 line.
3332 Paths in the DAG are represented with '|', '/' and so forth. ':' in place
3332 Paths in the DAG are represented with '|', '/' and so forth. ':' in place
3333 of a '|' indicates one or more revisions in a path are omitted.
3333 of a '|' indicates one or more revisions in a path are omitted.
3334
3334
3335 .. container:: verbose
3335 .. container:: verbose
3336
3336
3337 Use -L/--line-range FILE,M:N options to follow the history of lines
3337 Use -L/--line-range FILE,M:N options to follow the history of lines
3338 from M to N in FILE. With -p/--patch only diff hunks affecting
3338 from M to N in FILE. With -p/--patch only diff hunks affecting
3339 specified line range will be shown. This option requires --follow;
3339 specified line range will be shown. This option requires --follow;
3340 it can be specified multiple times. Currently, this option is not
3340 it can be specified multiple times. Currently, this option is not
3341 compatible with --graph. This option is experimental.
3341 compatible with --graph. This option is experimental.
3342
3342
3343 .. note::
3343 .. note::
3344
3344
3345 :hg:`log --patch` may generate unexpected diff output for merge
3345 :hg:`log --patch` may generate unexpected diff output for merge
3346 changesets, as it will only compare the merge changeset against
3346 changesets, as it will only compare the merge changeset against
3347 its first parent. Also, only files different from BOTH parents
3347 its first parent. Also, only files different from BOTH parents
3348 will appear in files:.
3348 will appear in files:.
3349
3349
3350 .. note::
3350 .. note::
3351
3351
3352 For performance reasons, :hg:`log FILE` may omit duplicate changes
3352 For performance reasons, :hg:`log FILE` may omit duplicate changes
3353 made on branches and will not show removals or mode changes. To
3353 made on branches and will not show removals or mode changes. To
3354 see all such changes, use the --removed switch.
3354 see all such changes, use the --removed switch.
3355
3355
3356 .. container:: verbose
3356 .. container:: verbose
3357
3357
3358 .. note::
3358 .. note::
3359
3359
3360 The history resulting from -L/--line-range options depends on diff
3360 The history resulting from -L/--line-range options depends on diff
3361 options; for instance if white-spaces are ignored, respective changes
3361 options; for instance if white-spaces are ignored, respective changes
3362 with only white-spaces in specified line range will not be listed.
3362 with only white-spaces in specified line range will not be listed.
3363
3363
3364 .. container:: verbose
3364 .. container:: verbose
3365
3365
3366 Some examples:
3366 Some examples:
3367
3367
3368 - changesets with full descriptions and file lists::
3368 - changesets with full descriptions and file lists::
3369
3369
3370 hg log -v
3370 hg log -v
3371
3371
3372 - changesets ancestral to the working directory::
3372 - changesets ancestral to the working directory::
3373
3373
3374 hg log -f
3374 hg log -f
3375
3375
3376 - last 10 commits on the current branch::
3376 - last 10 commits on the current branch::
3377
3377
3378 hg log -l 10 -b .
3378 hg log -l 10 -b .
3379
3379
3380 - changesets showing all modifications of a file, including removals::
3380 - changesets showing all modifications of a file, including removals::
3381
3381
3382 hg log --removed file.c
3382 hg log --removed file.c
3383
3383
3384 - all changesets that touch a directory, with diffs, excluding merges::
3384 - all changesets that touch a directory, with diffs, excluding merges::
3385
3385
3386 hg log -Mp lib/
3386 hg log -Mp lib/
3387
3387
3388 - all revision numbers that match a keyword::
3388 - all revision numbers that match a keyword::
3389
3389
3390 hg log -k bug --template "{rev}\\n"
3390 hg log -k bug --template "{rev}\\n"
3391
3391
3392 - the full hash identifier of the working directory parent::
3392 - the full hash identifier of the working directory parent::
3393
3393
3394 hg log -r . --template "{node}\\n"
3394 hg log -r . --template "{node}\\n"
3395
3395
3396 - list available log templates::
3396 - list available log templates::
3397
3397
3398 hg log -T list
3398 hg log -T list
3399
3399
3400 - check if a given changeset is included in a tagged release::
3400 - check if a given changeset is included in a tagged release::
3401
3401
3402 hg log -r "a21ccf and ancestor(1.9)"
3402 hg log -r "a21ccf and ancestor(1.9)"
3403
3403
3404 - find all changesets by some user in a date range::
3404 - find all changesets by some user in a date range::
3405
3405
3406 hg log -k alice -d "may 2008 to jul 2008"
3406 hg log -k alice -d "may 2008 to jul 2008"
3407
3407
3408 - summary of all changesets after the last tag::
3408 - summary of all changesets after the last tag::
3409
3409
3410 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3410 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3411
3411
3412 - changesets touching lines 13 to 23 for file.c::
3412 - changesets touching lines 13 to 23 for file.c::
3413
3413
3414 hg log -L file.c,13:23
3414 hg log -L file.c,13:23
3415
3415
3416 - changesets touching lines 13 to 23 for file.c and lines 2 to 6 of
3416 - changesets touching lines 13 to 23 for file.c and lines 2 to 6 of
3417 main.c with patch::
3417 main.c with patch::
3418
3418
3419 hg log -L file.c,13:23 -L main.c,2:6 -p
3419 hg log -L file.c,13:23 -L main.c,2:6 -p
3420
3420
3421 See :hg:`help dates` for a list of formats valid for -d/--date.
3421 See :hg:`help dates` for a list of formats valid for -d/--date.
3422
3422
3423 See :hg:`help revisions` for more about specifying and ordering
3423 See :hg:`help revisions` for more about specifying and ordering
3424 revisions.
3424 revisions.
3425
3425
3426 See :hg:`help templates` for more about pre-packaged styles and
3426 See :hg:`help templates` for more about pre-packaged styles and
3427 specifying custom templates. The default template used by the log
3427 specifying custom templates. The default template used by the log
3428 command can be customized via the ``ui.logtemplate`` configuration
3428 command can be customized via the ``ui.logtemplate`` configuration
3429 setting.
3429 setting.
3430
3430
3431 Returns 0 on success.
3431 Returns 0 on success.
3432
3432
3433 """
3433 """
3434 opts = pycompat.byteskwargs(opts)
3434 opts = pycompat.byteskwargs(opts)
3435 linerange = opts.get('line_range')
3435 linerange = opts.get('line_range')
3436
3436
3437 if linerange and not opts.get('follow'):
3437 if linerange and not opts.get('follow'):
3438 raise error.Abort(_('--line-range requires --follow'))
3438 raise error.Abort(_('--line-range requires --follow'))
3439
3439
3440 if linerange and pats:
3440 if linerange and pats:
3441 # TODO: take pats as patterns with no line-range filter
3441 # TODO: take pats as patterns with no line-range filter
3442 raise error.Abort(
3442 raise error.Abort(
3443 _('FILE arguments are not compatible with --line-range option')
3443 _('FILE arguments are not compatible with --line-range option')
3444 )
3444 )
3445
3445
3446 repo = scmutil.unhidehashlikerevs(repo, opts.get('rev'), 'nowarn')
3446 repo = scmutil.unhidehashlikerevs(repo, opts.get('rev'), 'nowarn')
3447 revs, differ = logcmdutil.getrevs(repo, pats, opts)
3447 revs, differ = logcmdutil.getrevs(repo, pats, opts)
3448 if linerange:
3448 if linerange:
3449 # TODO: should follow file history from logcmdutil._initialrevs(),
3449 # TODO: should follow file history from logcmdutil._initialrevs(),
3450 # then filter the result by logcmdutil._makerevset() and --limit
3450 # then filter the result by logcmdutil._makerevset() and --limit
3451 revs, differ = logcmdutil.getlinerangerevs(repo, revs, opts)
3451 revs, differ = logcmdutil.getlinerangerevs(repo, revs, opts)
3452
3452
3453 getrenamed = None
3453 getrenamed = None
3454 if opts.get('copies'):
3454 if opts.get('copies'):
3455 endrev = None
3455 endrev = None
3456 if opts.get('rev'):
3456 if opts.get('rev'):
3457 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
3457 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
3458 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3458 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3459
3459
3460 ui.pager('log')
3460 ui.pager('log')
3461 displayer = logcmdutil.changesetdisplayer(ui, repo, opts, differ,
3461 displayer = logcmdutil.changesetdisplayer(ui, repo, opts, differ,
3462 buffered=True)
3462 buffered=True)
3463 if opts.get('graph'):
3463 if opts.get('graph'):
3464 displayfn = logcmdutil.displaygraphrevs
3464 displayfn = logcmdutil.displaygraphrevs
3465 else:
3465 else:
3466 displayfn = logcmdutil.displayrevs
3466 displayfn = logcmdutil.displayrevs
3467 displayfn(ui, repo, revs, displayer, getrenamed)
3467 displayfn(ui, repo, revs, displayer, getrenamed)
3468
3468
3469 @command('manifest',
3469 @command('manifest',
3470 [('r', 'rev', '', _('revision to display'), _('REV')),
3470 [('r', 'rev', '', _('revision to display'), _('REV')),
3471 ('', 'all', False, _("list files from all revisions"))]
3471 ('', 'all', False, _("list files from all revisions"))]
3472 + formatteropts,
3472 + formatteropts,
3473 _('[-r REV]'), cmdtype=readonly)
3473 _('[-r REV]'), cmdtype=readonly)
3474 def manifest(ui, repo, node=None, rev=None, **opts):
3474 def manifest(ui, repo, node=None, rev=None, **opts):
3475 """output the current or given revision of the project manifest
3475 """output the current or given revision of the project manifest
3476
3476
3477 Print a list of version controlled files for the given revision.
3477 Print a list of version controlled files for the given revision.
3478 If no revision is given, the first parent of the working directory
3478 If no revision is given, the first parent of the working directory
3479 is used, or the null revision if no revision is checked out.
3479 is used, or the null revision if no revision is checked out.
3480
3480
3481 With -v, print file permissions, symlink and executable bits.
3481 With -v, print file permissions, symlink and executable bits.
3482 With --debug, print file revision hashes.
3482 With --debug, print file revision hashes.
3483
3483
3484 If option --all is specified, the list of all files from all revisions
3484 If option --all is specified, the list of all files from all revisions
3485 is printed. This includes deleted and renamed files.
3485 is printed. This includes deleted and renamed files.
3486
3486
3487 Returns 0 on success.
3487 Returns 0 on success.
3488 """
3488 """
3489 opts = pycompat.byteskwargs(opts)
3489 opts = pycompat.byteskwargs(opts)
3490 fm = ui.formatter('manifest', opts)
3490 fm = ui.formatter('manifest', opts)
3491
3491
3492 if opts.get('all'):
3492 if opts.get('all'):
3493 if rev or node:
3493 if rev or node:
3494 raise error.Abort(_("can't specify a revision with --all"))
3494 raise error.Abort(_("can't specify a revision with --all"))
3495
3495
3496 res = []
3496 res = []
3497 prefix = "data/"
3497 prefix = "data/"
3498 suffix = ".i"
3498 suffix = ".i"
3499 plen = len(prefix)
3499 plen = len(prefix)
3500 slen = len(suffix)
3500 slen = len(suffix)
3501 with repo.lock():
3501 with repo.lock():
3502 for fn, b, size in repo.store.datafiles():
3502 for fn, b, size in repo.store.datafiles():
3503 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3503 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3504 res.append(fn[plen:-slen])
3504 res.append(fn[plen:-slen])
3505 ui.pager('manifest')
3505 ui.pager('manifest')
3506 for f in res:
3506 for f in res:
3507 fm.startitem()
3507 fm.startitem()
3508 fm.write("path", '%s\n', f)
3508 fm.write("path", '%s\n', f)
3509 fm.end()
3509 fm.end()
3510 return
3510 return
3511
3511
3512 if rev and node:
3512 if rev and node:
3513 raise error.Abort(_("please specify just one revision"))
3513 raise error.Abort(_("please specify just one revision"))
3514
3514
3515 if not node:
3515 if not node:
3516 node = rev
3516 node = rev
3517
3517
3518 char = {'l': '@', 'x': '*', '': '', 't': 'd'}
3518 char = {'l': '@', 'x': '*', '': '', 't': 'd'}
3519 mode = {'l': '644', 'x': '755', '': '644', 't': '755'}
3519 mode = {'l': '644', 'x': '755', '': '644', 't': '755'}
3520 if node:
3520 if node:
3521 repo = scmutil.unhidehashlikerevs(repo, [node], 'nowarn')
3521 repo = scmutil.unhidehashlikerevs(repo, [node], 'nowarn')
3522 ctx = scmutil.revsingle(repo, node)
3522 ctx = scmutil.revsingle(repo, node)
3523 mf = ctx.manifest()
3523 mf = ctx.manifest()
3524 ui.pager('manifest')
3524 ui.pager('manifest')
3525 for f in ctx:
3525 for f in ctx:
3526 fm.startitem()
3526 fm.startitem()
3527 fl = ctx[f].flags()
3527 fl = ctx[f].flags()
3528 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
3528 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
3529 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
3529 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
3530 fm.write('path', '%s\n', f)
3530 fm.write('path', '%s\n', f)
3531 fm.end()
3531 fm.end()
3532
3532
3533 @command('^merge',
3533 @command('^merge',
3534 [('f', 'force', None,
3534 [('f', 'force', None,
3535 _('force a merge including outstanding changes (DEPRECATED)')),
3535 _('force a merge including outstanding changes (DEPRECATED)')),
3536 ('r', 'rev', '', _('revision to merge'), _('REV')),
3536 ('r', 'rev', '', _('revision to merge'), _('REV')),
3537 ('P', 'preview', None,
3537 ('P', 'preview', None,
3538 _('review revisions to merge (no merge is performed)')),
3538 _('review revisions to merge (no merge is performed)')),
3539 ('', 'abort', None, _('abort the ongoing merge')),
3539 ('', 'abort', None, _('abort the ongoing merge')),
3540 ] + mergetoolopts,
3540 ] + mergetoolopts,
3541 _('[-P] [[-r] REV]'))
3541 _('[-P] [[-r] REV]'))
3542 def merge(ui, repo, node=None, **opts):
3542 def merge(ui, repo, node=None, **opts):
3543 """merge another revision into working directory
3543 """merge another revision into working directory
3544
3544
3545 The current working directory is updated with all changes made in
3545 The current working directory is updated with all changes made in
3546 the requested revision since the last common predecessor revision.
3546 the requested revision since the last common predecessor revision.
3547
3547
3548 Files that changed between either parent are marked as changed for
3548 Files that changed between either parent are marked as changed for
3549 the next commit and a commit must be performed before any further
3549 the next commit and a commit must be performed before any further
3550 updates to the repository are allowed. The next commit will have
3550 updates to the repository are allowed. The next commit will have
3551 two parents.
3551 two parents.
3552
3552
3553 ``--tool`` can be used to specify the merge tool used for file
3553 ``--tool`` can be used to specify the merge tool used for file
3554 merges. It overrides the HGMERGE environment variable and your
3554 merges. It overrides the HGMERGE environment variable and your
3555 configuration files. See :hg:`help merge-tools` for options.
3555 configuration files. See :hg:`help merge-tools` for options.
3556
3556
3557 If no revision is specified, the working directory's parent is a
3557 If no revision is specified, the working directory's parent is a
3558 head revision, and the current branch contains exactly one other
3558 head revision, and the current branch contains exactly one other
3559 head, the other head is merged with by default. Otherwise, an
3559 head, the other head is merged with by default. Otherwise, an
3560 explicit revision with which to merge with must be provided.
3560 explicit revision with which to merge with must be provided.
3561
3561
3562 See :hg:`help resolve` for information on handling file conflicts.
3562 See :hg:`help resolve` for information on handling file conflicts.
3563
3563
3564 To undo an uncommitted merge, use :hg:`merge --abort` which
3564 To undo an uncommitted merge, use :hg:`merge --abort` which
3565 will check out a clean copy of the original merge parent, losing
3565 will check out a clean copy of the original merge parent, losing
3566 all changes.
3566 all changes.
3567
3567
3568 Returns 0 on success, 1 if there are unresolved files.
3568 Returns 0 on success, 1 if there are unresolved files.
3569 """
3569 """
3570
3570
3571 opts = pycompat.byteskwargs(opts)
3571 opts = pycompat.byteskwargs(opts)
3572 abort = opts.get('abort')
3572 abort = opts.get('abort')
3573 if abort and repo.dirstate.p2() == nullid:
3573 if abort and repo.dirstate.p2() == nullid:
3574 cmdutil.wrongtooltocontinue(repo, _('merge'))
3574 cmdutil.wrongtooltocontinue(repo, _('merge'))
3575 if abort:
3575 if abort:
3576 if node:
3576 if node:
3577 raise error.Abort(_("cannot specify a node with --abort"))
3577 raise error.Abort(_("cannot specify a node with --abort"))
3578 if opts.get('rev'):
3578 if opts.get('rev'):
3579 raise error.Abort(_("cannot specify both --rev and --abort"))
3579 raise error.Abort(_("cannot specify both --rev and --abort"))
3580 if opts.get('preview'):
3580 if opts.get('preview'):
3581 raise error.Abort(_("cannot specify --preview with --abort"))
3581 raise error.Abort(_("cannot specify --preview with --abort"))
3582 if opts.get('rev') and node:
3582 if opts.get('rev') and node:
3583 raise error.Abort(_("please specify just one revision"))
3583 raise error.Abort(_("please specify just one revision"))
3584 if not node:
3584 if not node:
3585 node = opts.get('rev')
3585 node = opts.get('rev')
3586
3586
3587 if node:
3587 if node:
3588 node = scmutil.revsingle(repo, node).node()
3588 node = scmutil.revsingle(repo, node).node()
3589
3589
3590 if not node and not abort:
3590 if not node and not abort:
3591 node = repo[destutil.destmerge(repo)].node()
3591 node = repo[destutil.destmerge(repo)].node()
3592
3592
3593 if opts.get('preview'):
3593 if opts.get('preview'):
3594 # find nodes that are ancestors of p2 but not of p1
3594 # find nodes that are ancestors of p2 but not of p1
3595 p1 = repo.lookup('.')
3595 p1 = repo.lookup('.')
3596 p2 = repo.lookup(node)
3596 p2 = repo.lookup(node)
3597 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3597 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3598
3598
3599 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
3599 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
3600 for node in nodes:
3600 for node in nodes:
3601 displayer.show(repo[node])
3601 displayer.show(repo[node])
3602 displayer.close()
3602 displayer.close()
3603 return 0
3603 return 0
3604
3604
3605 try:
3605 try:
3606 # ui.forcemerge is an internal variable, do not document
3606 # ui.forcemerge is an internal variable, do not document
3607 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
3607 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
3608 force = opts.get('force')
3608 force = opts.get('force')
3609 labels = ['working copy', 'merge rev']
3609 labels = ['working copy', 'merge rev']
3610 return hg.merge(repo, node, force=force, mergeforce=force,
3610 return hg.merge(repo, node, force=force, mergeforce=force,
3611 labels=labels, abort=abort)
3611 labels=labels, abort=abort)
3612 finally:
3612 finally:
3613 ui.setconfig('ui', 'forcemerge', '', 'merge')
3613 ui.setconfig('ui', 'forcemerge', '', 'merge')
3614
3614
3615 @command('outgoing|out',
3615 @command('outgoing|out',
3616 [('f', 'force', None, _('run even when the destination is unrelated')),
3616 [('f', 'force', None, _('run even when the destination is unrelated')),
3617 ('r', 'rev', [],
3617 ('r', 'rev', [],
3618 _('a changeset intended to be included in the destination'), _('REV')),
3618 _('a changeset intended to be included in the destination'), _('REV')),
3619 ('n', 'newest-first', None, _('show newest record first')),
3619 ('n', 'newest-first', None, _('show newest record first')),
3620 ('B', 'bookmarks', False, _('compare bookmarks')),
3620 ('B', 'bookmarks', False, _('compare bookmarks')),
3621 ('b', 'branch', [], _('a specific branch you would like to push'),
3621 ('b', 'branch', [], _('a specific branch you would like to push'),
3622 _('BRANCH')),
3622 _('BRANCH')),
3623 ] + logopts + remoteopts + subrepoopts,
3623 ] + logopts + remoteopts + subrepoopts,
3624 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3624 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3625 def outgoing(ui, repo, dest=None, **opts):
3625 def outgoing(ui, repo, dest=None, **opts):
3626 """show changesets not found in the destination
3626 """show changesets not found in the destination
3627
3627
3628 Show changesets not found in the specified destination repository
3628 Show changesets not found in the specified destination repository
3629 or the default push location. These are the changesets that would
3629 or the default push location. These are the changesets that would
3630 be pushed if a push was requested.
3630 be pushed if a push was requested.
3631
3631
3632 See pull for details of valid destination formats.
3632 See pull for details of valid destination formats.
3633
3633
3634 .. container:: verbose
3634 .. container:: verbose
3635
3635
3636 With -B/--bookmarks, the result of bookmark comparison between
3636 With -B/--bookmarks, the result of bookmark comparison between
3637 local and remote repositories is displayed. With -v/--verbose,
3637 local and remote repositories is displayed. With -v/--verbose,
3638 status is also displayed for each bookmark like below::
3638 status is also displayed for each bookmark like below::
3639
3639
3640 BM1 01234567890a added
3640 BM1 01234567890a added
3641 BM2 deleted
3641 BM2 deleted
3642 BM3 234567890abc advanced
3642 BM3 234567890abc advanced
3643 BM4 34567890abcd diverged
3643 BM4 34567890abcd diverged
3644 BM5 4567890abcde changed
3644 BM5 4567890abcde changed
3645
3645
3646 The action taken when pushing depends on the
3646 The action taken when pushing depends on the
3647 status of each bookmark:
3647 status of each bookmark:
3648
3648
3649 :``added``: push with ``-B`` will create it
3649 :``added``: push with ``-B`` will create it
3650 :``deleted``: push with ``-B`` will delete it
3650 :``deleted``: push with ``-B`` will delete it
3651 :``advanced``: push will update it
3651 :``advanced``: push will update it
3652 :``diverged``: push with ``-B`` will update it
3652 :``diverged``: push with ``-B`` will update it
3653 :``changed``: push with ``-B`` will update it
3653 :``changed``: push with ``-B`` will update it
3654
3654
3655 From the point of view of pushing behavior, bookmarks
3655 From the point of view of pushing behavior, bookmarks
3656 existing only in the remote repository are treated as
3656 existing only in the remote repository are treated as
3657 ``deleted``, even if it is in fact added remotely.
3657 ``deleted``, even if it is in fact added remotely.
3658
3658
3659 Returns 0 if there are outgoing changes, 1 otherwise.
3659 Returns 0 if there are outgoing changes, 1 otherwise.
3660 """
3660 """
3661 opts = pycompat.byteskwargs(opts)
3661 opts = pycompat.byteskwargs(opts)
3662 if opts.get('graph'):
3662 if opts.get('graph'):
3663 logcmdutil.checkunsupportedgraphflags([], opts)
3663 logcmdutil.checkunsupportedgraphflags([], opts)
3664 o, other = hg._outgoing(ui, repo, dest, opts)
3664 o, other = hg._outgoing(ui, repo, dest, opts)
3665 if not o:
3665 if not o:
3666 cmdutil.outgoinghooks(ui, repo, other, opts, o)
3666 cmdutil.outgoinghooks(ui, repo, other, opts, o)
3667 return
3667 return
3668
3668
3669 revdag = logcmdutil.graphrevs(repo, o, opts)
3669 revdag = logcmdutil.graphrevs(repo, o, opts)
3670 ui.pager('outgoing')
3670 ui.pager('outgoing')
3671 displayer = logcmdutil.changesetdisplayer(ui, repo, opts, buffered=True)
3671 displayer = logcmdutil.changesetdisplayer(ui, repo, opts, buffered=True)
3672 logcmdutil.displaygraph(ui, repo, revdag, displayer,
3672 logcmdutil.displaygraph(ui, repo, revdag, displayer,
3673 graphmod.asciiedges)
3673 graphmod.asciiedges)
3674 cmdutil.outgoinghooks(ui, repo, other, opts, o)
3674 cmdutil.outgoinghooks(ui, repo, other, opts, o)
3675 return 0
3675 return 0
3676
3676
3677 if opts.get('bookmarks'):
3677 if opts.get('bookmarks'):
3678 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3678 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3679 dest, branches = hg.parseurl(dest, opts.get('branch'))
3679 dest, branches = hg.parseurl(dest, opts.get('branch'))
3680 other = hg.peer(repo, opts, dest)
3680 other = hg.peer(repo, opts, dest)
3681 if 'bookmarks' not in other.listkeys('namespaces'):
3681 if 'bookmarks' not in other.listkeys('namespaces'):
3682 ui.warn(_("remote doesn't support bookmarks\n"))
3682 ui.warn(_("remote doesn't support bookmarks\n"))
3683 return 0
3683 return 0
3684 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3684 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3685 ui.pager('outgoing')
3685 ui.pager('outgoing')
3686 return bookmarks.outgoing(ui, repo, other)
3686 return bookmarks.outgoing(ui, repo, other)
3687
3687
3688 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3688 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3689 try:
3689 try:
3690 return hg.outgoing(ui, repo, dest, opts)
3690 return hg.outgoing(ui, repo, dest, opts)
3691 finally:
3691 finally:
3692 del repo._subtoppath
3692 del repo._subtoppath
3693
3693
3694 @command('parents',
3694 @command('parents',
3695 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3695 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3696 ] + templateopts,
3696 ] + templateopts,
3697 _('[-r REV] [FILE]'),
3697 _('[-r REV] [FILE]'),
3698 inferrepo=True)
3698 inferrepo=True)
3699 def parents(ui, repo, file_=None, **opts):
3699 def parents(ui, repo, file_=None, **opts):
3700 """show the parents of the working directory or revision (DEPRECATED)
3700 """show the parents of the working directory or revision (DEPRECATED)
3701
3701
3702 Print the working directory's parent revisions. If a revision is
3702 Print the working directory's parent revisions. If a revision is
3703 given via -r/--rev, the parent of that revision will be printed.
3703 given via -r/--rev, the parent of that revision will be printed.
3704 If a file argument is given, the revision in which the file was
3704 If a file argument is given, the revision in which the file was
3705 last changed (before the working directory revision or the
3705 last changed (before the working directory revision or the
3706 argument to --rev if given) is printed.
3706 argument to --rev if given) is printed.
3707
3707
3708 This command is equivalent to::
3708 This command is equivalent to::
3709
3709
3710 hg log -r "p1()+p2()" or
3710 hg log -r "p1()+p2()" or
3711 hg log -r "p1(REV)+p2(REV)" or
3711 hg log -r "p1(REV)+p2(REV)" or
3712 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
3712 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
3713 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
3713 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
3714
3714
3715 See :hg:`summary` and :hg:`help revsets` for related information.
3715 See :hg:`summary` and :hg:`help revsets` for related information.
3716
3716
3717 Returns 0 on success.
3717 Returns 0 on success.
3718 """
3718 """
3719
3719
3720 opts = pycompat.byteskwargs(opts)
3720 opts = pycompat.byteskwargs(opts)
3721 rev = opts.get('rev')
3721 rev = opts.get('rev')
3722 if rev:
3722 if rev:
3723 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
3723 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
3724 ctx = scmutil.revsingle(repo, rev, None)
3724 ctx = scmutil.revsingle(repo, rev, None)
3725
3725
3726 if file_:
3726 if file_:
3727 m = scmutil.match(ctx, (file_,), opts)
3727 m = scmutil.match(ctx, (file_,), opts)
3728 if m.anypats() or len(m.files()) != 1:
3728 if m.anypats() or len(m.files()) != 1:
3729 raise error.Abort(_('can only specify an explicit filename'))
3729 raise error.Abort(_('can only specify an explicit filename'))
3730 file_ = m.files()[0]
3730 file_ = m.files()[0]
3731 filenodes = []
3731 filenodes = []
3732 for cp in ctx.parents():
3732 for cp in ctx.parents():
3733 if not cp:
3733 if not cp:
3734 continue
3734 continue
3735 try:
3735 try:
3736 filenodes.append(cp.filenode(file_))
3736 filenodes.append(cp.filenode(file_))
3737 except error.LookupError:
3737 except error.LookupError:
3738 pass
3738 pass
3739 if not filenodes:
3739 if not filenodes:
3740 raise error.Abort(_("'%s' not found in manifest!") % file_)
3740 raise error.Abort(_("'%s' not found in manifest!") % file_)
3741 p = []
3741 p = []
3742 for fn in filenodes:
3742 for fn in filenodes:
3743 fctx = repo.filectx(file_, fileid=fn)
3743 fctx = repo.filectx(file_, fileid=fn)
3744 p.append(fctx.node())
3744 p.append(fctx.node())
3745 else:
3745 else:
3746 p = [cp.node() for cp in ctx.parents()]
3746 p = [cp.node() for cp in ctx.parents()]
3747
3747
3748 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
3748 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
3749 for n in p:
3749 for n in p:
3750 if n != nullid:
3750 if n != nullid:
3751 displayer.show(repo[n])
3751 displayer.show(repo[n])
3752 displayer.close()
3752 displayer.close()
3753
3753
3754 @command('paths', formatteropts, _('[NAME]'), optionalrepo=True,
3754 @command('paths', formatteropts, _('[NAME]'), optionalrepo=True,
3755 cmdtype=readonly)
3755 cmdtype=readonly)
3756 def paths(ui, repo, search=None, **opts):
3756 def paths(ui, repo, search=None, **opts):
3757 """show aliases for remote repositories
3757 """show aliases for remote repositories
3758
3758
3759 Show definition of symbolic path name NAME. If no name is given,
3759 Show definition of symbolic path name NAME. If no name is given,
3760 show definition of all available names.
3760 show definition of all available names.
3761
3761
3762 Option -q/--quiet suppresses all output when searching for NAME
3762 Option -q/--quiet suppresses all output when searching for NAME
3763 and shows only the path names when listing all definitions.
3763 and shows only the path names when listing all definitions.
3764
3764
3765 Path names are defined in the [paths] section of your
3765 Path names are defined in the [paths] section of your
3766 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3766 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3767 repository, ``.hg/hgrc`` is used, too.
3767 repository, ``.hg/hgrc`` is used, too.
3768
3768
3769 The path names ``default`` and ``default-push`` have a special
3769 The path names ``default`` and ``default-push`` have a special
3770 meaning. When performing a push or pull operation, they are used
3770 meaning. When performing a push or pull operation, they are used
3771 as fallbacks if no location is specified on the command-line.
3771 as fallbacks if no location is specified on the command-line.
3772 When ``default-push`` is set, it will be used for push and
3772 When ``default-push`` is set, it will be used for push and
3773 ``default`` will be used for pull; otherwise ``default`` is used
3773 ``default`` will be used for pull; otherwise ``default`` is used
3774 as the fallback for both. When cloning a repository, the clone
3774 as the fallback for both. When cloning a repository, the clone
3775 source is written as ``default`` in ``.hg/hgrc``.
3775 source is written as ``default`` in ``.hg/hgrc``.
3776
3776
3777 .. note::
3777 .. note::
3778
3778
3779 ``default`` and ``default-push`` apply to all inbound (e.g.
3779 ``default`` and ``default-push`` apply to all inbound (e.g.
3780 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
3780 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
3781 and :hg:`bundle`) operations.
3781 and :hg:`bundle`) operations.
3782
3782
3783 See :hg:`help urls` for more information.
3783 See :hg:`help urls` for more information.
3784
3784
3785 Returns 0 on success.
3785 Returns 0 on success.
3786 """
3786 """
3787
3787
3788 opts = pycompat.byteskwargs(opts)
3788 opts = pycompat.byteskwargs(opts)
3789 ui.pager('paths')
3789 ui.pager('paths')
3790 if search:
3790 if search:
3791 pathitems = [(name, path) for name, path in ui.paths.iteritems()
3791 pathitems = [(name, path) for name, path in ui.paths.iteritems()
3792 if name == search]
3792 if name == search]
3793 else:
3793 else:
3794 pathitems = sorted(ui.paths.iteritems())
3794 pathitems = sorted(ui.paths.iteritems())
3795
3795
3796 fm = ui.formatter('paths', opts)
3796 fm = ui.formatter('paths', opts)
3797 if fm.isplain():
3797 if fm.isplain():
3798 hidepassword = util.hidepassword
3798 hidepassword = util.hidepassword
3799 else:
3799 else:
3800 hidepassword = bytes
3800 hidepassword = bytes
3801 if ui.quiet:
3801 if ui.quiet:
3802 namefmt = '%s\n'
3802 namefmt = '%s\n'
3803 else:
3803 else:
3804 namefmt = '%s = '
3804 namefmt = '%s = '
3805 showsubopts = not search and not ui.quiet
3805 showsubopts = not search and not ui.quiet
3806
3806
3807 for name, path in pathitems:
3807 for name, path in pathitems:
3808 fm.startitem()
3808 fm.startitem()
3809 fm.condwrite(not search, 'name', namefmt, name)
3809 fm.condwrite(not search, 'name', namefmt, name)
3810 fm.condwrite(not ui.quiet, 'url', '%s\n', hidepassword(path.rawloc))
3810 fm.condwrite(not ui.quiet, 'url', '%s\n', hidepassword(path.rawloc))
3811 for subopt, value in sorted(path.suboptions.items()):
3811 for subopt, value in sorted(path.suboptions.items()):
3812 assert subopt not in ('name', 'url')
3812 assert subopt not in ('name', 'url')
3813 if showsubopts:
3813 if showsubopts:
3814 fm.plain('%s:%s = ' % (name, subopt))
3814 fm.plain('%s:%s = ' % (name, subopt))
3815 fm.condwrite(showsubopts, subopt, '%s\n', value)
3815 fm.condwrite(showsubopts, subopt, '%s\n', value)
3816
3816
3817 fm.end()
3817 fm.end()
3818
3818
3819 if search and not pathitems:
3819 if search and not pathitems:
3820 if not ui.quiet:
3820 if not ui.quiet:
3821 ui.warn(_("not found!\n"))
3821 ui.warn(_("not found!\n"))
3822 return 1
3822 return 1
3823 else:
3823 else:
3824 return 0
3824 return 0
3825
3825
3826 @command('phase',
3826 @command('phase',
3827 [('p', 'public', False, _('set changeset phase to public')),
3827 [('p', 'public', False, _('set changeset phase to public')),
3828 ('d', 'draft', False, _('set changeset phase to draft')),
3828 ('d', 'draft', False, _('set changeset phase to draft')),
3829 ('s', 'secret', False, _('set changeset phase to secret')),
3829 ('s', 'secret', False, _('set changeset phase to secret')),
3830 ('f', 'force', False, _('allow to move boundary backward')),
3830 ('f', 'force', False, _('allow to move boundary backward')),
3831 ('r', 'rev', [], _('target revision'), _('REV')),
3831 ('r', 'rev', [], _('target revision'), _('REV')),
3832 ],
3832 ],
3833 _('[-p|-d|-s] [-f] [-r] [REV...]'))
3833 _('[-p|-d|-s] [-f] [-r] [REV...]'))
3834 def phase(ui, repo, *revs, **opts):
3834 def phase(ui, repo, *revs, **opts):
3835 """set or show the current phase name
3835 """set or show the current phase name
3836
3836
3837 With no argument, show the phase name of the current revision(s).
3837 With no argument, show the phase name of the current revision(s).
3838
3838
3839 With one of -p/--public, -d/--draft or -s/--secret, change the
3839 With one of -p/--public, -d/--draft or -s/--secret, change the
3840 phase value of the specified revisions.
3840 phase value of the specified revisions.
3841
3841
3842 Unless -f/--force is specified, :hg:`phase` won't move changesets from a
3842 Unless -f/--force is specified, :hg:`phase` won't move changesets from a
3843 lower phase to a higher phase. Phases are ordered as follows::
3843 lower phase to a higher phase. Phases are ordered as follows::
3844
3844
3845 public < draft < secret
3845 public < draft < secret
3846
3846
3847 Returns 0 on success, 1 if some phases could not be changed.
3847 Returns 0 on success, 1 if some phases could not be changed.
3848
3848
3849 (For more information about the phases concept, see :hg:`help phases`.)
3849 (For more information about the phases concept, see :hg:`help phases`.)
3850 """
3850 """
3851 opts = pycompat.byteskwargs(opts)
3851 opts = pycompat.byteskwargs(opts)
3852 # search for a unique phase argument
3852 # search for a unique phase argument
3853 targetphase = None
3853 targetphase = None
3854 for idx, name in enumerate(phases.phasenames):
3854 for idx, name in enumerate(phases.phasenames):
3855 if opts[name]:
3855 if opts[name]:
3856 if targetphase is not None:
3856 if targetphase is not None:
3857 raise error.Abort(_('only one phase can be specified'))
3857 raise error.Abort(_('only one phase can be specified'))
3858 targetphase = idx
3858 targetphase = idx
3859
3859
3860 # look for specified revision
3860 # look for specified revision
3861 revs = list(revs)
3861 revs = list(revs)
3862 revs.extend(opts['rev'])
3862 revs.extend(opts['rev'])
3863 if not revs:
3863 if not revs:
3864 # display both parents as the second parent phase can influence
3864 # display both parents as the second parent phase can influence
3865 # the phase of a merge commit
3865 # the phase of a merge commit
3866 revs = [c.rev() for c in repo[None].parents()]
3866 revs = [c.rev() for c in repo[None].parents()]
3867
3867
3868 revs = scmutil.revrange(repo, revs)
3868 revs = scmutil.revrange(repo, revs)
3869
3869
3870 ret = 0
3870 ret = 0
3871 if targetphase is None:
3871 if targetphase is None:
3872 # display
3872 # display
3873 for r in revs:
3873 for r in revs:
3874 ctx = repo[r]
3874 ctx = repo[r]
3875 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
3875 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
3876 else:
3876 else:
3877 with repo.lock(), repo.transaction("phase") as tr:
3877 with repo.lock(), repo.transaction("phase") as tr:
3878 # set phase
3878 # set phase
3879 if not revs:
3879 if not revs:
3880 raise error.Abort(_('empty revision set'))
3880 raise error.Abort(_('empty revision set'))
3881 nodes = [repo[r].node() for r in revs]
3881 nodes = [repo[r].node() for r in revs]
3882 # moving revision from public to draft may hide them
3882 # moving revision from public to draft may hide them
3883 # We have to check result on an unfiltered repository
3883 # We have to check result on an unfiltered repository
3884 unfi = repo.unfiltered()
3884 unfi = repo.unfiltered()
3885 getphase = unfi._phasecache.phase
3885 getphase = unfi._phasecache.phase
3886 olddata = [getphase(unfi, r) for r in unfi]
3886 olddata = [getphase(unfi, r) for r in unfi]
3887 phases.advanceboundary(repo, tr, targetphase, nodes)
3887 phases.advanceboundary(repo, tr, targetphase, nodes)
3888 if opts['force']:
3888 if opts['force']:
3889 phases.retractboundary(repo, tr, targetphase, nodes)
3889 phases.retractboundary(repo, tr, targetphase, nodes)
3890 getphase = unfi._phasecache.phase
3890 getphase = unfi._phasecache.phase
3891 newdata = [getphase(unfi, r) for r in unfi]
3891 newdata = [getphase(unfi, r) for r in unfi]
3892 changes = sum(newdata[r] != olddata[r] for r in unfi)
3892 changes = sum(newdata[r] != olddata[r] for r in unfi)
3893 cl = unfi.changelog
3893 cl = unfi.changelog
3894 rejected = [n for n in nodes
3894 rejected = [n for n in nodes
3895 if newdata[cl.rev(n)] < targetphase]
3895 if newdata[cl.rev(n)] < targetphase]
3896 if rejected:
3896 if rejected:
3897 ui.warn(_('cannot move %i changesets to a higher '
3897 ui.warn(_('cannot move %i changesets to a higher '
3898 'phase, use --force\n') % len(rejected))
3898 'phase, use --force\n') % len(rejected))
3899 ret = 1
3899 ret = 1
3900 if changes:
3900 if changes:
3901 msg = _('phase changed for %i changesets\n') % changes
3901 msg = _('phase changed for %i changesets\n') % changes
3902 if ret:
3902 if ret:
3903 ui.status(msg)
3903 ui.status(msg)
3904 else:
3904 else:
3905 ui.note(msg)
3905 ui.note(msg)
3906 else:
3906 else:
3907 ui.warn(_('no phases changed\n'))
3907 ui.warn(_('no phases changed\n'))
3908 return ret
3908 return ret
3909
3909
3910 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
3910 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
3911 """Run after a changegroup has been added via pull/unbundle
3911 """Run after a changegroup has been added via pull/unbundle
3912
3912
3913 This takes arguments below:
3913 This takes arguments below:
3914
3914
3915 :modheads: change of heads by pull/unbundle
3915 :modheads: change of heads by pull/unbundle
3916 :optupdate: updating working directory is needed or not
3916 :optupdate: updating working directory is needed or not
3917 :checkout: update destination revision (or None to default destination)
3917 :checkout: update destination revision (or None to default destination)
3918 :brev: a name, which might be a bookmark to be activated after updating
3918 :brev: a name, which might be a bookmark to be activated after updating
3919 """
3919 """
3920 if modheads == 0:
3920 if modheads == 0:
3921 return
3921 return
3922 if optupdate:
3922 if optupdate:
3923 try:
3923 try:
3924 return hg.updatetotally(ui, repo, checkout, brev)
3924 return hg.updatetotally(ui, repo, checkout, brev)
3925 except error.UpdateAbort as inst:
3925 except error.UpdateAbort as inst:
3926 msg = _("not updating: %s") % stringutil.forcebytestr(inst)
3926 msg = _("not updating: %s") % stringutil.forcebytestr(inst)
3927 hint = inst.hint
3927 hint = inst.hint
3928 raise error.UpdateAbort(msg, hint=hint)
3928 raise error.UpdateAbort(msg, hint=hint)
3929 if modheads > 1:
3929 if modheads > 1:
3930 currentbranchheads = len(repo.branchheads())
3930 currentbranchheads = len(repo.branchheads())
3931 if currentbranchheads == modheads:
3931 if currentbranchheads == modheads:
3932 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3932 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3933 elif currentbranchheads > 1:
3933 elif currentbranchheads > 1:
3934 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
3934 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
3935 "merge)\n"))
3935 "merge)\n"))
3936 else:
3936 else:
3937 ui.status(_("(run 'hg heads' to see heads)\n"))
3937 ui.status(_("(run 'hg heads' to see heads)\n"))
3938 elif not ui.configbool('commands', 'update.requiredest'):
3938 elif not ui.configbool('commands', 'update.requiredest'):
3939 ui.status(_("(run 'hg update' to get a working copy)\n"))
3939 ui.status(_("(run 'hg update' to get a working copy)\n"))
3940
3940
3941 @command('^pull',
3941 @command('^pull',
3942 [('u', 'update', None,
3942 [('u', 'update', None,
3943 _('update to new branch head if new descendants were pulled')),
3943 _('update to new branch head if new descendants were pulled')),
3944 ('f', 'force', None, _('run even when remote repository is unrelated')),
3944 ('f', 'force', None, _('run even when remote repository is unrelated')),
3945 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3945 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3946 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3946 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3947 ('b', 'branch', [], _('a specific branch you would like to pull'),
3947 ('b', 'branch', [], _('a specific branch you would like to pull'),
3948 _('BRANCH')),
3948 _('BRANCH')),
3949 ] + remoteopts,
3949 ] + remoteopts,
3950 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
3950 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
3951 def pull(ui, repo, source="default", **opts):
3951 def pull(ui, repo, source="default", **opts):
3952 """pull changes from the specified source
3952 """pull changes from the specified source
3953
3953
3954 Pull changes from a remote repository to a local one.
3954 Pull changes from a remote repository to a local one.
3955
3955
3956 This finds all changes from the repository at the specified path
3956 This finds all changes from the repository at the specified path
3957 or URL and adds them to a local repository (the current one unless
3957 or URL and adds them to a local repository (the current one unless
3958 -R is specified). By default, this does not update the copy of the
3958 -R is specified). By default, this does not update the copy of the
3959 project in the working directory.
3959 project in the working directory.
3960
3960
3961 Use :hg:`incoming` if you want to see what would have been added
3961 Use :hg:`incoming` if you want to see what would have been added
3962 by a pull at the time you issued this command. If you then decide
3962 by a pull at the time you issued this command. If you then decide
3963 to add those changes to the repository, you should use :hg:`pull
3963 to add those changes to the repository, you should use :hg:`pull
3964 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
3964 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
3965
3965
3966 If SOURCE is omitted, the 'default' path will be used.
3966 If SOURCE is omitted, the 'default' path will be used.
3967 See :hg:`help urls` for more information.
3967 See :hg:`help urls` for more information.
3968
3968
3969 Specifying bookmark as ``.`` is equivalent to specifying the active
3969 Specifying bookmark as ``.`` is equivalent to specifying the active
3970 bookmark's name.
3970 bookmark's name.
3971
3971
3972 Returns 0 on success, 1 if an update had unresolved files.
3972 Returns 0 on success, 1 if an update had unresolved files.
3973 """
3973 """
3974
3974
3975 opts = pycompat.byteskwargs(opts)
3975 opts = pycompat.byteskwargs(opts)
3976 if ui.configbool('commands', 'update.requiredest') and opts.get('update'):
3976 if ui.configbool('commands', 'update.requiredest') and opts.get('update'):
3977 msg = _('update destination required by configuration')
3977 msg = _('update destination required by configuration')
3978 hint = _('use hg pull followed by hg update DEST')
3978 hint = _('use hg pull followed by hg update DEST')
3979 raise error.Abort(msg, hint=hint)
3979 raise error.Abort(msg, hint=hint)
3980
3980
3981 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
3981 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
3982 ui.status(_('pulling from %s\n') % util.hidepassword(source))
3982 ui.status(_('pulling from %s\n') % util.hidepassword(source))
3983 other = hg.peer(repo, opts, source)
3983 other = hg.peer(repo, opts, source)
3984 try:
3984 try:
3985 revs, checkout = hg.addbranchrevs(repo, other, branches,
3985 revs, checkout = hg.addbranchrevs(repo, other, branches,
3986 opts.get('rev'))
3986 opts.get('rev'))
3987
3987
3988
3988
3989 pullopargs = {}
3989 pullopargs = {}
3990 if opts.get('bookmark'):
3990 if opts.get('bookmark'):
3991 if not revs:
3991 if not revs:
3992 revs = []
3992 revs = []
3993 # The list of bookmark used here is not the one used to actually
3993 # The list of bookmark used here is not the one used to actually
3994 # update the bookmark name. This can result in the revision pulled
3994 # update the bookmark name. This can result in the revision pulled
3995 # not ending up with the name of the bookmark because of a race
3995 # not ending up with the name of the bookmark because of a race
3996 # condition on the server. (See issue 4689 for details)
3996 # condition on the server. (See issue 4689 for details)
3997 remotebookmarks = other.listkeys('bookmarks')
3997 remotebookmarks = other.listkeys('bookmarks')
3998 remotebookmarks = bookmarks.unhexlifybookmarks(remotebookmarks)
3998 remotebookmarks = bookmarks.unhexlifybookmarks(remotebookmarks)
3999 pullopargs['remotebookmarks'] = remotebookmarks
3999 pullopargs['remotebookmarks'] = remotebookmarks
4000 for b in opts['bookmark']:
4000 for b in opts['bookmark']:
4001 b = repo._bookmarks.expandname(b)
4001 b = repo._bookmarks.expandname(b)
4002 if b not in remotebookmarks:
4002 if b not in remotebookmarks:
4003 raise error.Abort(_('remote bookmark %s not found!') % b)
4003 raise error.Abort(_('remote bookmark %s not found!') % b)
4004 revs.append(hex(remotebookmarks[b]))
4004 revs.append(hex(remotebookmarks[b]))
4005
4005
4006 if revs:
4006 if revs:
4007 try:
4007 try:
4008 # When 'rev' is a bookmark name, we cannot guarantee that it
4008 # When 'rev' is a bookmark name, we cannot guarantee that it
4009 # will be updated with that name because of a race condition
4009 # will be updated with that name because of a race condition
4010 # server side. (See issue 4689 for details)
4010 # server side. (See issue 4689 for details)
4011 oldrevs = revs
4011 oldrevs = revs
4012 revs = [] # actually, nodes
4012 revs = [] # actually, nodes
4013 for r in oldrevs:
4013 for r in oldrevs:
4014 node = other.lookup(r)
4014 node = other.lookup(r)
4015 revs.append(node)
4015 revs.append(node)
4016 if r == checkout:
4016 if r == checkout:
4017 checkout = node
4017 checkout = node
4018 except error.CapabilityError:
4018 except error.CapabilityError:
4019 err = _("other repository doesn't support revision lookup, "
4019 err = _("other repository doesn't support revision lookup, "
4020 "so a rev cannot be specified.")
4020 "so a rev cannot be specified.")
4021 raise error.Abort(err)
4021 raise error.Abort(err)
4022
4022
4023 wlock = util.nullcontextmanager()
4023 wlock = util.nullcontextmanager()
4024 if opts.get('update'):
4024 if opts.get('update'):
4025 wlock = repo.wlock()
4025 wlock = repo.wlock()
4026 with wlock:
4026 with wlock:
4027 pullopargs.update(opts.get('opargs', {}))
4027 pullopargs.update(opts.get('opargs', {}))
4028 modheads = exchange.pull(repo, other, heads=revs,
4028 modheads = exchange.pull(repo, other, heads=revs,
4029 force=opts.get('force'),
4029 force=opts.get('force'),
4030 bookmarks=opts.get('bookmark', ()),
4030 bookmarks=opts.get('bookmark', ()),
4031 opargs=pullopargs).cgresult
4031 opargs=pullopargs).cgresult
4032
4032
4033 # brev is a name, which might be a bookmark to be activated at
4033 # brev is a name, which might be a bookmark to be activated at
4034 # the end of the update. In other words, it is an explicit
4034 # the end of the update. In other words, it is an explicit
4035 # destination of the update
4035 # destination of the update
4036 brev = None
4036 brev = None
4037
4037
4038 if checkout:
4038 if checkout:
4039 checkout = "%d" % repo.changelog.rev(checkout)
4039 checkout = "%d" % repo.changelog.rev(checkout)
4040
4040
4041 # order below depends on implementation of
4041 # order below depends on implementation of
4042 # hg.addbranchrevs(). opts['bookmark'] is ignored,
4042 # hg.addbranchrevs(). opts['bookmark'] is ignored,
4043 # because 'checkout' is determined without it.
4043 # because 'checkout' is determined without it.
4044 if opts.get('rev'):
4044 if opts.get('rev'):
4045 brev = opts['rev'][0]
4045 brev = opts['rev'][0]
4046 elif opts.get('branch'):
4046 elif opts.get('branch'):
4047 brev = opts['branch'][0]
4047 brev = opts['branch'][0]
4048 else:
4048 else:
4049 brev = branches[0]
4049 brev = branches[0]
4050 repo._subtoppath = source
4050 repo._subtoppath = source
4051 try:
4051 try:
4052 ret = postincoming(ui, repo, modheads, opts.get('update'),
4052 ret = postincoming(ui, repo, modheads, opts.get('update'),
4053 checkout, brev)
4053 checkout, brev)
4054
4054
4055 finally:
4055 finally:
4056 del repo._subtoppath
4056 del repo._subtoppath
4057
4057
4058 finally:
4058 finally:
4059 other.close()
4059 other.close()
4060 return ret
4060 return ret
4061
4061
4062 @command('^push',
4062 @command('^push',
4063 [('f', 'force', None, _('force push')),
4063 [('f', 'force', None, _('force push')),
4064 ('r', 'rev', [],
4064 ('r', 'rev', [],
4065 _('a changeset intended to be included in the destination'),
4065 _('a changeset intended to be included in the destination'),
4066 _('REV')),
4066 _('REV')),
4067 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4067 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4068 ('b', 'branch', [],
4068 ('b', 'branch', [],
4069 _('a specific branch you would like to push'), _('BRANCH')),
4069 _('a specific branch you would like to push'), _('BRANCH')),
4070 ('', 'new-branch', False, _('allow pushing a new branch')),
4070 ('', 'new-branch', False, _('allow pushing a new branch')),
4071 ('', 'pushvars', [], _('variables that can be sent to server (ADVANCED)')),
4071 ('', 'pushvars', [], _('variables that can be sent to server (ADVANCED)')),
4072 ] + remoteopts,
4072 ] + remoteopts,
4073 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4073 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4074 def push(ui, repo, dest=None, **opts):
4074 def push(ui, repo, dest=None, **opts):
4075 """push changes to the specified destination
4075 """push changes to the specified destination
4076
4076
4077 Push changesets from the local repository to the specified
4077 Push changesets from the local repository to the specified
4078 destination.
4078 destination.
4079
4079
4080 This operation is symmetrical to pull: it is identical to a pull
4080 This operation is symmetrical to pull: it is identical to a pull
4081 in the destination repository from the current one.
4081 in the destination repository from the current one.
4082
4082
4083 By default, push will not allow creation of new heads at the
4083 By default, push will not allow creation of new heads at the
4084 destination, since multiple heads would make it unclear which head
4084 destination, since multiple heads would make it unclear which head
4085 to use. In this situation, it is recommended to pull and merge
4085 to use. In this situation, it is recommended to pull and merge
4086 before pushing.
4086 before pushing.
4087
4087
4088 Use --new-branch if you want to allow push to create a new named
4088 Use --new-branch if you want to allow push to create a new named
4089 branch that is not present at the destination. This allows you to
4089 branch that is not present at the destination. This allows you to
4090 only create a new branch without forcing other changes.
4090 only create a new branch without forcing other changes.
4091
4091
4092 .. note::
4092 .. note::
4093
4093
4094 Extra care should be taken with the -f/--force option,
4094 Extra care should be taken with the -f/--force option,
4095 which will push all new heads on all branches, an action which will
4095 which will push all new heads on all branches, an action which will
4096 almost always cause confusion for collaborators.
4096 almost always cause confusion for collaborators.
4097
4097
4098 If -r/--rev is used, the specified revision and all its ancestors
4098 If -r/--rev is used, the specified revision and all its ancestors
4099 will be pushed to the remote repository.
4099 will be pushed to the remote repository.
4100
4100
4101 If -B/--bookmark is used, the specified bookmarked revision, its
4101 If -B/--bookmark is used, the specified bookmarked revision, its
4102 ancestors, and the bookmark will be pushed to the remote
4102 ancestors, and the bookmark will be pushed to the remote
4103 repository. Specifying ``.`` is equivalent to specifying the active
4103 repository. Specifying ``.`` is equivalent to specifying the active
4104 bookmark's name.
4104 bookmark's name.
4105
4105
4106 Please see :hg:`help urls` for important details about ``ssh://``
4106 Please see :hg:`help urls` for important details about ``ssh://``
4107 URLs. If DESTINATION is omitted, a default path will be used.
4107 URLs. If DESTINATION is omitted, a default path will be used.
4108
4108
4109 .. container:: verbose
4109 .. container:: verbose
4110
4110
4111 The --pushvars option sends strings to the server that become
4111 The --pushvars option sends strings to the server that become
4112 environment variables prepended with ``HG_USERVAR_``. For example,
4112 environment variables prepended with ``HG_USERVAR_``. For example,
4113 ``--pushvars ENABLE_FEATURE=true``, provides the server side hooks with
4113 ``--pushvars ENABLE_FEATURE=true``, provides the server side hooks with
4114 ``HG_USERVAR_ENABLE_FEATURE=true`` as part of their environment.
4114 ``HG_USERVAR_ENABLE_FEATURE=true`` as part of their environment.
4115
4115
4116 pushvars can provide for user-overridable hooks as well as set debug
4116 pushvars can provide for user-overridable hooks as well as set debug
4117 levels. One example is having a hook that blocks commits containing
4117 levels. One example is having a hook that blocks commits containing
4118 conflict markers, but enables the user to override the hook if the file
4118 conflict markers, but enables the user to override the hook if the file
4119 is using conflict markers for testing purposes or the file format has
4119 is using conflict markers for testing purposes or the file format has
4120 strings that look like conflict markers.
4120 strings that look like conflict markers.
4121
4121
4122 By default, servers will ignore `--pushvars`. To enable it add the
4122 By default, servers will ignore `--pushvars`. To enable it add the
4123 following to your configuration file::
4123 following to your configuration file::
4124
4124
4125 [push]
4125 [push]
4126 pushvars.server = true
4126 pushvars.server = true
4127
4127
4128 Returns 0 if push was successful, 1 if nothing to push.
4128 Returns 0 if push was successful, 1 if nothing to push.
4129 """
4129 """
4130
4130
4131 opts = pycompat.byteskwargs(opts)
4131 opts = pycompat.byteskwargs(opts)
4132 if opts.get('bookmark'):
4132 if opts.get('bookmark'):
4133 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
4133 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
4134 for b in opts['bookmark']:
4134 for b in opts['bookmark']:
4135 # translate -B options to -r so changesets get pushed
4135 # translate -B options to -r so changesets get pushed
4136 b = repo._bookmarks.expandname(b)
4136 b = repo._bookmarks.expandname(b)
4137 if b in repo._bookmarks:
4137 if b in repo._bookmarks:
4138 opts.setdefault('rev', []).append(b)
4138 opts.setdefault('rev', []).append(b)
4139 else:
4139 else:
4140 # if we try to push a deleted bookmark, translate it to null
4140 # if we try to push a deleted bookmark, translate it to null
4141 # this lets simultaneous -r, -b options continue working
4141 # this lets simultaneous -r, -b options continue working
4142 opts.setdefault('rev', []).append("null")
4142 opts.setdefault('rev', []).append("null")
4143
4143
4144 path = ui.paths.getpath(dest, default=('default-push', 'default'))
4144 path = ui.paths.getpath(dest, default=('default-push', 'default'))
4145 if not path:
4145 if not path:
4146 raise error.Abort(_('default repository not configured!'),
4146 raise error.Abort(_('default repository not configured!'),
4147 hint=_("see 'hg help config.paths'"))
4147 hint=_("see 'hg help config.paths'"))
4148 dest = path.pushloc or path.loc
4148 dest = path.pushloc or path.loc
4149 branches = (path.branch, opts.get('branch') or [])
4149 branches = (path.branch, opts.get('branch') or [])
4150 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4150 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4151 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4151 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4152 other = hg.peer(repo, opts, dest)
4152 other = hg.peer(repo, opts, dest)
4153
4153
4154 if revs:
4154 if revs:
4155 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4155 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4156 if not revs:
4156 if not revs:
4157 raise error.Abort(_("specified revisions evaluate to an empty set"),
4157 raise error.Abort(_("specified revisions evaluate to an empty set"),
4158 hint=_("use different revision arguments"))
4158 hint=_("use different revision arguments"))
4159 elif path.pushrev:
4159 elif path.pushrev:
4160 # It doesn't make any sense to specify ancestor revisions. So limit
4160 # It doesn't make any sense to specify ancestor revisions. So limit
4161 # to DAG heads to make discovery simpler.
4161 # to DAG heads to make discovery simpler.
4162 expr = revsetlang.formatspec('heads(%r)', path.pushrev)
4162 expr = revsetlang.formatspec('heads(%r)', path.pushrev)
4163 revs = scmutil.revrange(repo, [expr])
4163 revs = scmutil.revrange(repo, [expr])
4164 revs = [repo[rev].node() for rev in revs]
4164 revs = [repo[rev].node() for rev in revs]
4165 if not revs:
4165 if not revs:
4166 raise error.Abort(_('default push revset for path evaluates to an '
4166 raise error.Abort(_('default push revset for path evaluates to an '
4167 'empty set'))
4167 'empty set'))
4168
4168
4169 repo._subtoppath = dest
4169 repo._subtoppath = dest
4170 try:
4170 try:
4171 # push subrepos depth-first for coherent ordering
4171 # push subrepos depth-first for coherent ordering
4172 c = repo['.']
4172 c = repo['.']
4173 subs = c.substate # only repos that are committed
4173 subs = c.substate # only repos that are committed
4174 for s in sorted(subs):
4174 for s in sorted(subs):
4175 result = c.sub(s).push(opts)
4175 result = c.sub(s).push(opts)
4176 if result == 0:
4176 if result == 0:
4177 return not result
4177 return not result
4178 finally:
4178 finally:
4179 del repo._subtoppath
4179 del repo._subtoppath
4180
4180
4181 opargs = dict(opts.get('opargs', {})) # copy opargs since we may mutate it
4181 opargs = dict(opts.get('opargs', {})) # copy opargs since we may mutate it
4182 opargs.setdefault('pushvars', []).extend(opts.get('pushvars', []))
4182 opargs.setdefault('pushvars', []).extend(opts.get('pushvars', []))
4183
4183
4184 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
4184 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
4185 newbranch=opts.get('new_branch'),
4185 newbranch=opts.get('new_branch'),
4186 bookmarks=opts.get('bookmark', ()),
4186 bookmarks=opts.get('bookmark', ()),
4187 opargs=opargs)
4187 opargs=opargs)
4188
4188
4189 result = not pushop.cgresult
4189 result = not pushop.cgresult
4190
4190
4191 if pushop.bkresult is not None:
4191 if pushop.bkresult is not None:
4192 if pushop.bkresult == 2:
4192 if pushop.bkresult == 2:
4193 result = 2
4193 result = 2
4194 elif not result and pushop.bkresult:
4194 elif not result and pushop.bkresult:
4195 result = 2
4195 result = 2
4196
4196
4197 return result
4197 return result
4198
4198
4199 @command('recover', [])
4199 @command('recover', [])
4200 def recover(ui, repo):
4200 def recover(ui, repo):
4201 """roll back an interrupted transaction
4201 """roll back an interrupted transaction
4202
4202
4203 Recover from an interrupted commit or pull.
4203 Recover from an interrupted commit or pull.
4204
4204
4205 This command tries to fix the repository status after an
4205 This command tries to fix the repository status after an
4206 interrupted operation. It should only be necessary when Mercurial
4206 interrupted operation. It should only be necessary when Mercurial
4207 suggests it.
4207 suggests it.
4208
4208
4209 Returns 0 if successful, 1 if nothing to recover or verify fails.
4209 Returns 0 if successful, 1 if nothing to recover or verify fails.
4210 """
4210 """
4211 if repo.recover():
4211 if repo.recover():
4212 return hg.verify(repo)
4212 return hg.verify(repo)
4213 return 1
4213 return 1
4214
4214
4215 @command('^remove|rm',
4215 @command('^remove|rm',
4216 [('A', 'after', None, _('record delete for missing files')),
4216 [('A', 'after', None, _('record delete for missing files')),
4217 ('f', 'force', None,
4217 ('f', 'force', None,
4218 _('forget added files, delete modified files')),
4218 _('forget added files, delete modified files')),
4219 ] + subrepoopts + walkopts + dryrunopts,
4219 ] + subrepoopts + walkopts + dryrunopts,
4220 _('[OPTION]... FILE...'),
4220 _('[OPTION]... FILE...'),
4221 inferrepo=True)
4221 inferrepo=True)
4222 def remove(ui, repo, *pats, **opts):
4222 def remove(ui, repo, *pats, **opts):
4223 """remove the specified files on the next commit
4223 """remove the specified files on the next commit
4224
4224
4225 Schedule the indicated files for removal from the current branch.
4225 Schedule the indicated files for removal from the current branch.
4226
4226
4227 This command schedules the files to be removed at the next commit.
4227 This command schedules the files to be removed at the next commit.
4228 To undo a remove before that, see :hg:`revert`. To undo added
4228 To undo a remove before that, see :hg:`revert`. To undo added
4229 files, see :hg:`forget`.
4229 files, see :hg:`forget`.
4230
4230
4231 .. container:: verbose
4231 .. container:: verbose
4232
4232
4233 -A/--after can be used to remove only files that have already
4233 -A/--after can be used to remove only files that have already
4234 been deleted, -f/--force can be used to force deletion, and -Af
4234 been deleted, -f/--force can be used to force deletion, and -Af
4235 can be used to remove files from the next revision without
4235 can be used to remove files from the next revision without
4236 deleting them from the working directory.
4236 deleting them from the working directory.
4237
4237
4238 The following table details the behavior of remove for different
4238 The following table details the behavior of remove for different
4239 file states (columns) and option combinations (rows). The file
4239 file states (columns) and option combinations (rows). The file
4240 states are Added [A], Clean [C], Modified [M] and Missing [!]
4240 states are Added [A], Clean [C], Modified [M] and Missing [!]
4241 (as reported by :hg:`status`). The actions are Warn, Remove
4241 (as reported by :hg:`status`). The actions are Warn, Remove
4242 (from branch) and Delete (from disk):
4242 (from branch) and Delete (from disk):
4243
4243
4244 ========= == == == ==
4244 ========= == == == ==
4245 opt/state A C M !
4245 opt/state A C M !
4246 ========= == == == ==
4246 ========= == == == ==
4247 none W RD W R
4247 none W RD W R
4248 -f R RD RD R
4248 -f R RD RD R
4249 -A W W W R
4249 -A W W W R
4250 -Af R R R R
4250 -Af R R R R
4251 ========= == == == ==
4251 ========= == == == ==
4252
4252
4253 .. note::
4253 .. note::
4254
4254
4255 :hg:`remove` never deletes files in Added [A] state from the
4255 :hg:`remove` never deletes files in Added [A] state from the
4256 working directory, not even if ``--force`` is specified.
4256 working directory, not even if ``--force`` is specified.
4257
4257
4258 Returns 0 on success, 1 if any warnings encountered.
4258 Returns 0 on success, 1 if any warnings encountered.
4259 """
4259 """
4260
4260
4261 opts = pycompat.byteskwargs(opts)
4261 opts = pycompat.byteskwargs(opts)
4262 after, force = opts.get('after'), opts.get('force')
4262 after, force = opts.get('after'), opts.get('force')
4263 dryrun = opts.get('dry_run')
4263 dryrun = opts.get('dry_run')
4264 if not pats and not after:
4264 if not pats and not after:
4265 raise error.Abort(_('no files specified'))
4265 raise error.Abort(_('no files specified'))
4266
4266
4267 m = scmutil.match(repo[None], pats, opts)
4267 m = scmutil.match(repo[None], pats, opts)
4268 subrepos = opts.get('subrepos')
4268 subrepos = opts.get('subrepos')
4269 return cmdutil.remove(ui, repo, m, "", after, force, subrepos,
4269 return cmdutil.remove(ui, repo, m, "", after, force, subrepos,
4270 dryrun=dryrun)
4270 dryrun=dryrun)
4271
4271
4272 @command('rename|move|mv',
4272 @command('rename|move|mv',
4273 [('A', 'after', None, _('record a rename that has already occurred')),
4273 [('A', 'after', None, _('record a rename that has already occurred')),
4274 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4274 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4275 ] + walkopts + dryrunopts,
4275 ] + walkopts + dryrunopts,
4276 _('[OPTION]... SOURCE... DEST'))
4276 _('[OPTION]... SOURCE... DEST'))
4277 def rename(ui, repo, *pats, **opts):
4277 def rename(ui, repo, *pats, **opts):
4278 """rename files; equivalent of copy + remove
4278 """rename files; equivalent of copy + remove
4279
4279
4280 Mark dest as copies of sources; mark sources for deletion. If dest
4280 Mark dest as copies of sources; mark sources for deletion. If dest
4281 is a directory, copies are put in that directory. If dest is a
4281 is a directory, copies are put in that directory. If dest is a
4282 file, there can only be one source.
4282 file, there can only be one source.
4283
4283
4284 By default, this command copies the contents of files as they
4284 By default, this command copies the contents of files as they
4285 exist in the working directory. If invoked with -A/--after, the
4285 exist in the working directory. If invoked with -A/--after, the
4286 operation is recorded, but no copying is performed.
4286 operation is recorded, but no copying is performed.
4287
4287
4288 This command takes effect at the next commit. To undo a rename
4288 This command takes effect at the next commit. To undo a rename
4289 before that, see :hg:`revert`.
4289 before that, see :hg:`revert`.
4290
4290
4291 Returns 0 on success, 1 if errors are encountered.
4291 Returns 0 on success, 1 if errors are encountered.
4292 """
4292 """
4293 opts = pycompat.byteskwargs(opts)
4293 opts = pycompat.byteskwargs(opts)
4294 with repo.wlock(False):
4294 with repo.wlock(False):
4295 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4295 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4296
4296
4297 @command('resolve',
4297 @command('resolve',
4298 [('a', 'all', None, _('select all unresolved files')),
4298 [('a', 'all', None, _('select all unresolved files')),
4299 ('l', 'list', None, _('list state of files needing merge')),
4299 ('l', 'list', None, _('list state of files needing merge')),
4300 ('m', 'mark', None, _('mark files as resolved')),
4300 ('m', 'mark', None, _('mark files as resolved')),
4301 ('u', 'unmark', None, _('mark files as unresolved')),
4301 ('u', 'unmark', None, _('mark files as unresolved')),
4302 ('n', 'no-status', None, _('hide status prefix'))]
4302 ('n', 'no-status', None, _('hide status prefix'))]
4303 + mergetoolopts + walkopts + formatteropts,
4303 + mergetoolopts + walkopts + formatteropts,
4304 _('[OPTION]... [FILE]...'),
4304 _('[OPTION]... [FILE]...'),
4305 inferrepo=True)
4305 inferrepo=True)
4306 def resolve(ui, repo, *pats, **opts):
4306 def resolve(ui, repo, *pats, **opts):
4307 """redo merges or set/view the merge status of files
4307 """redo merges or set/view the merge status of files
4308
4308
4309 Merges with unresolved conflicts are often the result of
4309 Merges with unresolved conflicts are often the result of
4310 non-interactive merging using the ``internal:merge`` configuration
4310 non-interactive merging using the ``internal:merge`` configuration
4311 setting, or a command-line merge tool like ``diff3``. The resolve
4311 setting, or a command-line merge tool like ``diff3``. The resolve
4312 command is used to manage the files involved in a merge, after
4312 command is used to manage the files involved in a merge, after
4313 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4313 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4314 working directory must have two parents). See :hg:`help
4314 working directory must have two parents). See :hg:`help
4315 merge-tools` for information on configuring merge tools.
4315 merge-tools` for information on configuring merge tools.
4316
4316
4317 The resolve command can be used in the following ways:
4317 The resolve command can be used in the following ways:
4318
4318
4319 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4319 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4320 files, discarding any previous merge attempts. Re-merging is not
4320 files, discarding any previous merge attempts. Re-merging is not
4321 performed for files already marked as resolved. Use ``--all/-a``
4321 performed for files already marked as resolved. Use ``--all/-a``
4322 to select all unresolved files. ``--tool`` can be used to specify
4322 to select all unresolved files. ``--tool`` can be used to specify
4323 the merge tool used for the given files. It overrides the HGMERGE
4323 the merge tool used for the given files. It overrides the HGMERGE
4324 environment variable and your configuration files. Previous file
4324 environment variable and your configuration files. Previous file
4325 contents are saved with a ``.orig`` suffix.
4325 contents are saved with a ``.orig`` suffix.
4326
4326
4327 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4327 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4328 (e.g. after having manually fixed-up the files). The default is
4328 (e.g. after having manually fixed-up the files). The default is
4329 to mark all unresolved files.
4329 to mark all unresolved files.
4330
4330
4331 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4331 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4332 default is to mark all resolved files.
4332 default is to mark all resolved files.
4333
4333
4334 - :hg:`resolve -l`: list files which had or still have conflicts.
4334 - :hg:`resolve -l`: list files which had or still have conflicts.
4335 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4335 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4336 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
4336 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
4337 the list. See :hg:`help filesets` for details.
4337 the list. See :hg:`help filesets` for details.
4338
4338
4339 .. note::
4339 .. note::
4340
4340
4341 Mercurial will not let you commit files with unresolved merge
4341 Mercurial will not let you commit files with unresolved merge
4342 conflicts. You must use :hg:`resolve -m ...` before you can
4342 conflicts. You must use :hg:`resolve -m ...` before you can
4343 commit after a conflicting merge.
4343 commit after a conflicting merge.
4344
4344
4345 Returns 0 on success, 1 if any files fail a resolve attempt.
4345 Returns 0 on success, 1 if any files fail a resolve attempt.
4346 """
4346 """
4347
4347
4348 opts = pycompat.byteskwargs(opts)
4348 opts = pycompat.byteskwargs(opts)
4349 flaglist = 'all mark unmark list no_status'.split()
4349 flaglist = 'all mark unmark list no_status'.split()
4350 all, mark, unmark, show, nostatus = \
4350 all, mark, unmark, show, nostatus = \
4351 [opts.get(o) for o in flaglist]
4351 [opts.get(o) for o in flaglist]
4352
4352
4353 if (show and (mark or unmark)) or (mark and unmark):
4353 if (show and (mark or unmark)) or (mark and unmark):
4354 raise error.Abort(_("too many options specified"))
4354 raise error.Abort(_("too many options specified"))
4355 if pats and all:
4355 if pats and all:
4356 raise error.Abort(_("can't specify --all and patterns"))
4356 raise error.Abort(_("can't specify --all and patterns"))
4357 if not (all or pats or show or mark or unmark):
4357 if not (all or pats or show or mark or unmark):
4358 raise error.Abort(_('no files or directories specified'),
4358 raise error.Abort(_('no files or directories specified'),
4359 hint=('use --all to re-merge all unresolved files'))
4359 hint=('use --all to re-merge all unresolved files'))
4360
4360
4361 if show:
4361 if show:
4362 ui.pager('resolve')
4362 ui.pager('resolve')
4363 fm = ui.formatter('resolve', opts)
4363 fm = ui.formatter('resolve', opts)
4364 ms = mergemod.mergestate.read(repo)
4364 ms = mergemod.mergestate.read(repo)
4365 m = scmutil.match(repo[None], pats, opts)
4365 m = scmutil.match(repo[None], pats, opts)
4366
4366
4367 # Labels and keys based on merge state. Unresolved path conflicts show
4367 # Labels and keys based on merge state. Unresolved path conflicts show
4368 # as 'P'. Resolved path conflicts show as 'R', the same as normal
4368 # as 'P'. Resolved path conflicts show as 'R', the same as normal
4369 # resolved conflicts.
4369 # resolved conflicts.
4370 mergestateinfo = {
4370 mergestateinfo = {
4371 mergemod.MERGE_RECORD_UNRESOLVED: ('resolve.unresolved', 'U'),
4371 mergemod.MERGE_RECORD_UNRESOLVED: ('resolve.unresolved', 'U'),
4372 mergemod.MERGE_RECORD_RESOLVED: ('resolve.resolved', 'R'),
4372 mergemod.MERGE_RECORD_RESOLVED: ('resolve.resolved', 'R'),
4373 mergemod.MERGE_RECORD_UNRESOLVED_PATH: ('resolve.unresolved', 'P'),
4373 mergemod.MERGE_RECORD_UNRESOLVED_PATH: ('resolve.unresolved', 'P'),
4374 mergemod.MERGE_RECORD_RESOLVED_PATH: ('resolve.resolved', 'R'),
4374 mergemod.MERGE_RECORD_RESOLVED_PATH: ('resolve.resolved', 'R'),
4375 mergemod.MERGE_RECORD_DRIVER_RESOLVED: ('resolve.driverresolved',
4375 mergemod.MERGE_RECORD_DRIVER_RESOLVED: ('resolve.driverresolved',
4376 'D'),
4376 'D'),
4377 }
4377 }
4378
4378
4379 for f in ms:
4379 for f in ms:
4380 if not m(f):
4380 if not m(f):
4381 continue
4381 continue
4382
4382
4383 label, key = mergestateinfo[ms[f]]
4383 label, key = mergestateinfo[ms[f]]
4384 fm.startitem()
4384 fm.startitem()
4385 fm.condwrite(not nostatus, 'status', '%s ', key, label=label)
4385 fm.condwrite(not nostatus, 'status', '%s ', key, label=label)
4386 fm.write('path', '%s\n', f, label=label)
4386 fm.write('path', '%s\n', f, label=label)
4387 fm.end()
4387 fm.end()
4388 return 0
4388 return 0
4389
4389
4390 with repo.wlock():
4390 with repo.wlock():
4391 ms = mergemod.mergestate.read(repo)
4391 ms = mergemod.mergestate.read(repo)
4392
4392
4393 if not (ms.active() or repo.dirstate.p2() != nullid):
4393 if not (ms.active() or repo.dirstate.p2() != nullid):
4394 raise error.Abort(
4394 raise error.Abort(
4395 _('resolve command not applicable when not merging'))
4395 _('resolve command not applicable when not merging'))
4396
4396
4397 wctx = repo[None]
4397 wctx = repo[None]
4398
4398
4399 if (ms.mergedriver
4399 if (ms.mergedriver
4400 and ms.mdstate() == mergemod.MERGE_DRIVER_STATE_UNMARKED):
4400 and ms.mdstate() == mergemod.MERGE_DRIVER_STATE_UNMARKED):
4401 proceed = mergemod.driverpreprocess(repo, ms, wctx)
4401 proceed = mergemod.driverpreprocess(repo, ms, wctx)
4402 ms.commit()
4402 ms.commit()
4403 # allow mark and unmark to go through
4403 # allow mark and unmark to go through
4404 if not mark and not unmark and not proceed:
4404 if not mark and not unmark and not proceed:
4405 return 1
4405 return 1
4406
4406
4407 m = scmutil.match(wctx, pats, opts)
4407 m = scmutil.match(wctx, pats, opts)
4408 ret = 0
4408 ret = 0
4409 didwork = False
4409 didwork = False
4410 runconclude = False
4410 runconclude = False
4411
4411
4412 tocomplete = []
4412 tocomplete = []
4413 for f in ms:
4413 for f in ms:
4414 if not m(f):
4414 if not m(f):
4415 continue
4415 continue
4416
4416
4417 didwork = True
4417 didwork = True
4418
4418
4419 # don't let driver-resolved files be marked, and run the conclude
4419 # don't let driver-resolved files be marked, and run the conclude
4420 # step if asked to resolve
4420 # step if asked to resolve
4421 if ms[f] == mergemod.MERGE_RECORD_DRIVER_RESOLVED:
4421 if ms[f] == mergemod.MERGE_RECORD_DRIVER_RESOLVED:
4422 exact = m.exact(f)
4422 exact = m.exact(f)
4423 if mark:
4423 if mark:
4424 if exact:
4424 if exact:
4425 ui.warn(_('not marking %s as it is driver-resolved\n')
4425 ui.warn(_('not marking %s as it is driver-resolved\n')
4426 % f)
4426 % f)
4427 elif unmark:
4427 elif unmark:
4428 if exact:
4428 if exact:
4429 ui.warn(_('not unmarking %s as it is driver-resolved\n')
4429 ui.warn(_('not unmarking %s as it is driver-resolved\n')
4430 % f)
4430 % f)
4431 else:
4431 else:
4432 runconclude = True
4432 runconclude = True
4433 continue
4433 continue
4434
4434
4435 # path conflicts must be resolved manually
4435 # path conflicts must be resolved manually
4436 if ms[f] in (mergemod.MERGE_RECORD_UNRESOLVED_PATH,
4436 if ms[f] in (mergemod.MERGE_RECORD_UNRESOLVED_PATH,
4437 mergemod.MERGE_RECORD_RESOLVED_PATH):
4437 mergemod.MERGE_RECORD_RESOLVED_PATH):
4438 if mark:
4438 if mark:
4439 ms.mark(f, mergemod.MERGE_RECORD_RESOLVED_PATH)
4439 ms.mark(f, mergemod.MERGE_RECORD_RESOLVED_PATH)
4440 elif unmark:
4440 elif unmark:
4441 ms.mark(f, mergemod.MERGE_RECORD_UNRESOLVED_PATH)
4441 ms.mark(f, mergemod.MERGE_RECORD_UNRESOLVED_PATH)
4442 elif ms[f] == mergemod.MERGE_RECORD_UNRESOLVED_PATH:
4442 elif ms[f] == mergemod.MERGE_RECORD_UNRESOLVED_PATH:
4443 ui.warn(_('%s: path conflict must be resolved manually\n')
4443 ui.warn(_('%s: path conflict must be resolved manually\n')
4444 % f)
4444 % f)
4445 continue
4445 continue
4446
4446
4447 if mark:
4447 if mark:
4448 ms.mark(f, mergemod.MERGE_RECORD_RESOLVED)
4448 ms.mark(f, mergemod.MERGE_RECORD_RESOLVED)
4449 elif unmark:
4449 elif unmark:
4450 ms.mark(f, mergemod.MERGE_RECORD_UNRESOLVED)
4450 ms.mark(f, mergemod.MERGE_RECORD_UNRESOLVED)
4451 else:
4451 else:
4452 # backup pre-resolve (merge uses .orig for its own purposes)
4452 # backup pre-resolve (merge uses .orig for its own purposes)
4453 a = repo.wjoin(f)
4453 a = repo.wjoin(f)
4454 try:
4454 try:
4455 util.copyfile(a, a + ".resolve")
4455 util.copyfile(a, a + ".resolve")
4456 except (IOError, OSError) as inst:
4456 except (IOError, OSError) as inst:
4457 if inst.errno != errno.ENOENT:
4457 if inst.errno != errno.ENOENT:
4458 raise
4458 raise
4459
4459
4460 try:
4460 try:
4461 # preresolve file
4461 # preresolve file
4462 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4462 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4463 'resolve')
4463 'resolve')
4464 complete, r = ms.preresolve(f, wctx)
4464 complete, r = ms.preresolve(f, wctx)
4465 if not complete:
4465 if not complete:
4466 tocomplete.append(f)
4466 tocomplete.append(f)
4467 elif r:
4467 elif r:
4468 ret = 1
4468 ret = 1
4469 finally:
4469 finally:
4470 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4470 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4471 ms.commit()
4471 ms.commit()
4472
4472
4473 # replace filemerge's .orig file with our resolve file, but only
4473 # replace filemerge's .orig file with our resolve file, but only
4474 # for merges that are complete
4474 # for merges that are complete
4475 if complete:
4475 if complete:
4476 try:
4476 try:
4477 util.rename(a + ".resolve",
4477 util.rename(a + ".resolve",
4478 scmutil.origpath(ui, repo, a))
4478 scmutil.origpath(ui, repo, a))
4479 except OSError as inst:
4479 except OSError as inst:
4480 if inst.errno != errno.ENOENT:
4480 if inst.errno != errno.ENOENT:
4481 raise
4481 raise
4482
4482
4483 for f in tocomplete:
4483 for f in tocomplete:
4484 try:
4484 try:
4485 # resolve file
4485 # resolve file
4486 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4486 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4487 'resolve')
4487 'resolve')
4488 r = ms.resolve(f, wctx)
4488 r = ms.resolve(f, wctx)
4489 if r:
4489 if r:
4490 ret = 1
4490 ret = 1
4491 finally:
4491 finally:
4492 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4492 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4493 ms.commit()
4493 ms.commit()
4494
4494
4495 # replace filemerge's .orig file with our resolve file
4495 # replace filemerge's .orig file with our resolve file
4496 a = repo.wjoin(f)
4496 a = repo.wjoin(f)
4497 try:
4497 try:
4498 util.rename(a + ".resolve", scmutil.origpath(ui, repo, a))
4498 util.rename(a + ".resolve", scmutil.origpath(ui, repo, a))
4499 except OSError as inst:
4499 except OSError as inst:
4500 if inst.errno != errno.ENOENT:
4500 if inst.errno != errno.ENOENT:
4501 raise
4501 raise
4502
4502
4503 ms.commit()
4503 ms.commit()
4504 ms.recordactions()
4504 ms.recordactions()
4505
4505
4506 if not didwork and pats:
4506 if not didwork and pats:
4507 hint = None
4507 hint = None
4508 if not any([p for p in pats if p.find(':') >= 0]):
4508 if not any([p for p in pats if p.find(':') >= 0]):
4509 pats = ['path:%s' % p for p in pats]
4509 pats = ['path:%s' % p for p in pats]
4510 m = scmutil.match(wctx, pats, opts)
4510 m = scmutil.match(wctx, pats, opts)
4511 for f in ms:
4511 for f in ms:
4512 if not m(f):
4512 if not m(f):
4513 continue
4513 continue
4514 flags = ''.join(['-%s ' % o[0:1] for o in flaglist
4514 flags = ''.join(['-%s ' % o[0:1] for o in flaglist
4515 if opts.get(o)])
4515 if opts.get(o)])
4516 hint = _("(try: hg resolve %s%s)\n") % (
4516 hint = _("(try: hg resolve %s%s)\n") % (
4517 flags,
4517 flags,
4518 ' '.join(pats))
4518 ' '.join(pats))
4519 break
4519 break
4520 ui.warn(_("arguments do not match paths that need resolving\n"))
4520 ui.warn(_("arguments do not match paths that need resolving\n"))
4521 if hint:
4521 if hint:
4522 ui.warn(hint)
4522 ui.warn(hint)
4523 elif ms.mergedriver and ms.mdstate() != 's':
4523 elif ms.mergedriver and ms.mdstate() != 's':
4524 # run conclude step when either a driver-resolved file is requested
4524 # run conclude step when either a driver-resolved file is requested
4525 # or there are no driver-resolved files
4525 # or there are no driver-resolved files
4526 # we can't use 'ret' to determine whether any files are unresolved
4526 # we can't use 'ret' to determine whether any files are unresolved
4527 # because we might not have tried to resolve some
4527 # because we might not have tried to resolve some
4528 if ((runconclude or not list(ms.driverresolved()))
4528 if ((runconclude or not list(ms.driverresolved()))
4529 and not list(ms.unresolved())):
4529 and not list(ms.unresolved())):
4530 proceed = mergemod.driverconclude(repo, ms, wctx)
4530 proceed = mergemod.driverconclude(repo, ms, wctx)
4531 ms.commit()
4531 ms.commit()
4532 if not proceed:
4532 if not proceed:
4533 return 1
4533 return 1
4534
4534
4535 # Nudge users into finishing an unfinished operation
4535 # Nudge users into finishing an unfinished operation
4536 unresolvedf = list(ms.unresolved())
4536 unresolvedf = list(ms.unresolved())
4537 driverresolvedf = list(ms.driverresolved())
4537 driverresolvedf = list(ms.driverresolved())
4538 if not unresolvedf and not driverresolvedf:
4538 if not unresolvedf and not driverresolvedf:
4539 ui.status(_('(no more unresolved files)\n'))
4539 ui.status(_('(no more unresolved files)\n'))
4540 cmdutil.checkafterresolved(repo)
4540 cmdutil.checkafterresolved(repo)
4541 elif not unresolvedf:
4541 elif not unresolvedf:
4542 ui.status(_('(no more unresolved files -- '
4542 ui.status(_('(no more unresolved files -- '
4543 'run "hg resolve --all" to conclude)\n'))
4543 'run "hg resolve --all" to conclude)\n'))
4544
4544
4545 return ret
4545 return ret
4546
4546
4547 @command('revert',
4547 @command('revert',
4548 [('a', 'all', None, _('revert all changes when no arguments given')),
4548 [('a', 'all', None, _('revert all changes when no arguments given')),
4549 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4549 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4550 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4550 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4551 ('C', 'no-backup', None, _('do not save backup copies of files')),
4551 ('C', 'no-backup', None, _('do not save backup copies of files')),
4552 ('i', 'interactive', None, _('interactively select the changes')),
4552 ('i', 'interactive', None, _('interactively select the changes')),
4553 ] + walkopts + dryrunopts,
4553 ] + walkopts + dryrunopts,
4554 _('[OPTION]... [-r REV] [NAME]...'))
4554 _('[OPTION]... [-r REV] [NAME]...'))
4555 def revert(ui, repo, *pats, **opts):
4555 def revert(ui, repo, *pats, **opts):
4556 """restore files to their checkout state
4556 """restore files to their checkout state
4557
4557
4558 .. note::
4558 .. note::
4559
4559
4560 To check out earlier revisions, you should use :hg:`update REV`.
4560 To check out earlier revisions, you should use :hg:`update REV`.
4561 To cancel an uncommitted merge (and lose your changes),
4561 To cancel an uncommitted merge (and lose your changes),
4562 use :hg:`merge --abort`.
4562 use :hg:`merge --abort`.
4563
4563
4564 With no revision specified, revert the specified files or directories
4564 With no revision specified, revert the specified files or directories
4565 to the contents they had in the parent of the working directory.
4565 to the contents they had in the parent of the working directory.
4566 This restores the contents of files to an unmodified
4566 This restores the contents of files to an unmodified
4567 state and unschedules adds, removes, copies, and renames. If the
4567 state and unschedules adds, removes, copies, and renames. If the
4568 working directory has two parents, you must explicitly specify a
4568 working directory has two parents, you must explicitly specify a
4569 revision.
4569 revision.
4570
4570
4571 Using the -r/--rev or -d/--date options, revert the given files or
4571 Using the -r/--rev or -d/--date options, revert the given files or
4572 directories to their states as of a specific revision. Because
4572 directories to their states as of a specific revision. Because
4573 revert does not change the working directory parents, this will
4573 revert does not change the working directory parents, this will
4574 cause these files to appear modified. This can be helpful to "back
4574 cause these files to appear modified. This can be helpful to "back
4575 out" some or all of an earlier change. See :hg:`backout` for a
4575 out" some or all of an earlier change. See :hg:`backout` for a
4576 related method.
4576 related method.
4577
4577
4578 Modified files are saved with a .orig suffix before reverting.
4578 Modified files are saved with a .orig suffix before reverting.
4579 To disable these backups, use --no-backup. It is possible to store
4579 To disable these backups, use --no-backup. It is possible to store
4580 the backup files in a custom directory relative to the root of the
4580 the backup files in a custom directory relative to the root of the
4581 repository by setting the ``ui.origbackuppath`` configuration
4581 repository by setting the ``ui.origbackuppath`` configuration
4582 option.
4582 option.
4583
4583
4584 See :hg:`help dates` for a list of formats valid for -d/--date.
4584 See :hg:`help dates` for a list of formats valid for -d/--date.
4585
4585
4586 See :hg:`help backout` for a way to reverse the effect of an
4586 See :hg:`help backout` for a way to reverse the effect of an
4587 earlier changeset.
4587 earlier changeset.
4588
4588
4589 Returns 0 on success.
4589 Returns 0 on success.
4590 """
4590 """
4591
4591
4592 opts = pycompat.byteskwargs(opts)
4592 opts = pycompat.byteskwargs(opts)
4593 if opts.get("date"):
4593 if opts.get("date"):
4594 if opts.get("rev"):
4594 if opts.get("rev"):
4595 raise error.Abort(_("you can't specify a revision and a date"))
4595 raise error.Abort(_("you can't specify a revision and a date"))
4596 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4596 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4597
4597
4598 parent, p2 = repo.dirstate.parents()
4598 parent, p2 = repo.dirstate.parents()
4599 if not opts.get('rev') and p2 != nullid:
4599 if not opts.get('rev') and p2 != nullid:
4600 # revert after merge is a trap for new users (issue2915)
4600 # revert after merge is a trap for new users (issue2915)
4601 raise error.Abort(_('uncommitted merge with no revision specified'),
4601 raise error.Abort(_('uncommitted merge with no revision specified'),
4602 hint=_("use 'hg update' or see 'hg help revert'"))
4602 hint=_("use 'hg update' or see 'hg help revert'"))
4603
4603
4604 rev = opts.get('rev')
4604 rev = opts.get('rev')
4605 if rev:
4605 if rev:
4606 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
4606 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
4607 ctx = scmutil.revsingle(repo, rev)
4607 ctx = scmutil.revsingle(repo, rev)
4608
4608
4609 if (not (pats or opts.get('include') or opts.get('exclude') or
4609 if (not (pats or opts.get('include') or opts.get('exclude') or
4610 opts.get('all') or opts.get('interactive'))):
4610 opts.get('all') or opts.get('interactive'))):
4611 msg = _("no files or directories specified")
4611 msg = _("no files or directories specified")
4612 if p2 != nullid:
4612 if p2 != nullid:
4613 hint = _("uncommitted merge, use --all to discard all changes,"
4613 hint = _("uncommitted merge, use --all to discard all changes,"
4614 " or 'hg update -C .' to abort the merge")
4614 " or 'hg update -C .' to abort the merge")
4615 raise error.Abort(msg, hint=hint)
4615 raise error.Abort(msg, hint=hint)
4616 dirty = any(repo.status())
4616 dirty = any(repo.status())
4617 node = ctx.node()
4617 node = ctx.node()
4618 if node != parent:
4618 if node != parent:
4619 if dirty:
4619 if dirty:
4620 hint = _("uncommitted changes, use --all to discard all"
4620 hint = _("uncommitted changes, use --all to discard all"
4621 " changes, or 'hg update %s' to update") % ctx.rev()
4621 " changes, or 'hg update %s' to update") % ctx.rev()
4622 else:
4622 else:
4623 hint = _("use --all to revert all files,"
4623 hint = _("use --all to revert all files,"
4624 " or 'hg update %s' to update") % ctx.rev()
4624 " or 'hg update %s' to update") % ctx.rev()
4625 elif dirty:
4625 elif dirty:
4626 hint = _("uncommitted changes, use --all to discard all changes")
4626 hint = _("uncommitted changes, use --all to discard all changes")
4627 else:
4627 else:
4628 hint = _("use --all to revert all files")
4628 hint = _("use --all to revert all files")
4629 raise error.Abort(msg, hint=hint)
4629 raise error.Abort(msg, hint=hint)
4630
4630
4631 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats,
4631 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats,
4632 **pycompat.strkwargs(opts))
4632 **pycompat.strkwargs(opts))
4633
4633
4634 @command('rollback', dryrunopts +
4634 @command('rollback', dryrunopts +
4635 [('f', 'force', False, _('ignore safety measures'))])
4635 [('f', 'force', False, _('ignore safety measures'))])
4636 def rollback(ui, repo, **opts):
4636 def rollback(ui, repo, **opts):
4637 """roll back the last transaction (DANGEROUS) (DEPRECATED)
4637 """roll back the last transaction (DANGEROUS) (DEPRECATED)
4638
4638
4639 Please use :hg:`commit --amend` instead of rollback to correct
4639 Please use :hg:`commit --amend` instead of rollback to correct
4640 mistakes in the last commit.
4640 mistakes in the last commit.
4641
4641
4642 This command should be used with care. There is only one level of
4642 This command should be used with care. There is only one level of
4643 rollback, and there is no way to undo a rollback. It will also
4643 rollback, and there is no way to undo a rollback. It will also
4644 restore the dirstate at the time of the last transaction, losing
4644 restore the dirstate at the time of the last transaction, losing
4645 any dirstate changes since that time. This command does not alter
4645 any dirstate changes since that time. This command does not alter
4646 the working directory.
4646 the working directory.
4647
4647
4648 Transactions are used to encapsulate the effects of all commands
4648 Transactions are used to encapsulate the effects of all commands
4649 that create new changesets or propagate existing changesets into a
4649 that create new changesets or propagate existing changesets into a
4650 repository.
4650 repository.
4651
4651
4652 .. container:: verbose
4652 .. container:: verbose
4653
4653
4654 For example, the following commands are transactional, and their
4654 For example, the following commands are transactional, and their
4655 effects can be rolled back:
4655 effects can be rolled back:
4656
4656
4657 - commit
4657 - commit
4658 - import
4658 - import
4659 - pull
4659 - pull
4660 - push (with this repository as the destination)
4660 - push (with this repository as the destination)
4661 - unbundle
4661 - unbundle
4662
4662
4663 To avoid permanent data loss, rollback will refuse to rollback a
4663 To avoid permanent data loss, rollback will refuse to rollback a
4664 commit transaction if it isn't checked out. Use --force to
4664 commit transaction if it isn't checked out. Use --force to
4665 override this protection.
4665 override this protection.
4666
4666
4667 The rollback command can be entirely disabled by setting the
4667 The rollback command can be entirely disabled by setting the
4668 ``ui.rollback`` configuration setting to false. If you're here
4668 ``ui.rollback`` configuration setting to false. If you're here
4669 because you want to use rollback and it's disabled, you can
4669 because you want to use rollback and it's disabled, you can
4670 re-enable the command by setting ``ui.rollback`` to true.
4670 re-enable the command by setting ``ui.rollback`` to true.
4671
4671
4672 This command is not intended for use on public repositories. Once
4672 This command is not intended for use on public repositories. Once
4673 changes are visible for pull by other users, rolling a transaction
4673 changes are visible for pull by other users, rolling a transaction
4674 back locally is ineffective (someone else may already have pulled
4674 back locally is ineffective (someone else may already have pulled
4675 the changes). Furthermore, a race is possible with readers of the
4675 the changes). Furthermore, a race is possible with readers of the
4676 repository; for example an in-progress pull from the repository
4676 repository; for example an in-progress pull from the repository
4677 may fail if a rollback is performed.
4677 may fail if a rollback is performed.
4678
4678
4679 Returns 0 on success, 1 if no rollback data is available.
4679 Returns 0 on success, 1 if no rollback data is available.
4680 """
4680 """
4681 if not ui.configbool('ui', 'rollback'):
4681 if not ui.configbool('ui', 'rollback'):
4682 raise error.Abort(_('rollback is disabled because it is unsafe'),
4682 raise error.Abort(_('rollback is disabled because it is unsafe'),
4683 hint=('see `hg help -v rollback` for information'))
4683 hint=('see `hg help -v rollback` for information'))
4684 return repo.rollback(dryrun=opts.get(r'dry_run'),
4684 return repo.rollback(dryrun=opts.get(r'dry_run'),
4685 force=opts.get(r'force'))
4685 force=opts.get(r'force'))
4686
4686
4687 @command('root', [], cmdtype=readonly)
4687 @command('root', [], cmdtype=readonly)
4688 def root(ui, repo):
4688 def root(ui, repo):
4689 """print the root (top) of the current working directory
4689 """print the root (top) of the current working directory
4690
4690
4691 Print the root directory of the current repository.
4691 Print the root directory of the current repository.
4692
4692
4693 Returns 0 on success.
4693 Returns 0 on success.
4694 """
4694 """
4695 ui.write(repo.root + "\n")
4695 ui.write(repo.root + "\n")
4696
4696
4697 @command('^serve',
4697 @command('^serve',
4698 [('A', 'accesslog', '', _('name of access log file to write to'),
4698 [('A', 'accesslog', '', _('name of access log file to write to'),
4699 _('FILE')),
4699 _('FILE')),
4700 ('d', 'daemon', None, _('run server in background')),
4700 ('d', 'daemon', None, _('run server in background')),
4701 ('', 'daemon-postexec', [], _('used internally by daemon mode')),
4701 ('', 'daemon-postexec', [], _('used internally by daemon mode')),
4702 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4702 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4703 # use string type, then we can check if something was passed
4703 # use string type, then we can check if something was passed
4704 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4704 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4705 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4705 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4706 _('ADDR')),
4706 _('ADDR')),
4707 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4707 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4708 _('PREFIX')),
4708 _('PREFIX')),
4709 ('n', 'name', '',
4709 ('n', 'name', '',
4710 _('name to show in web pages (default: working directory)'), _('NAME')),
4710 _('name to show in web pages (default: working directory)'), _('NAME')),
4711 ('', 'web-conf', '',
4711 ('', 'web-conf', '',
4712 _("name of the hgweb config file (see 'hg help hgweb')"), _('FILE')),
4712 _("name of the hgweb config file (see 'hg help hgweb')"), _('FILE')),
4713 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4713 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4714 _('FILE')),
4714 _('FILE')),
4715 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4715 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4716 ('', 'stdio', None, _('for remote clients (ADVANCED)')),
4716 ('', 'stdio', None, _('for remote clients (ADVANCED)')),
4717 ('', 'cmdserver', '', _('for remote clients (ADVANCED)'), _('MODE')),
4717 ('', 'cmdserver', '', _('for remote clients (ADVANCED)'), _('MODE')),
4718 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4718 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4719 ('', 'style', '', _('template style to use'), _('STYLE')),
4719 ('', 'style', '', _('template style to use'), _('STYLE')),
4720 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4720 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4721 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))]
4721 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))]
4722 + subrepoopts,
4722 + subrepoopts,
4723 _('[OPTION]...'),
4723 _('[OPTION]...'),
4724 optionalrepo=True)
4724 optionalrepo=True)
4725 def serve(ui, repo, **opts):
4725 def serve(ui, repo, **opts):
4726 """start stand-alone webserver
4726 """start stand-alone webserver
4727
4727
4728 Start a local HTTP repository browser and pull server. You can use
4728 Start a local HTTP repository browser and pull server. You can use
4729 this for ad-hoc sharing and browsing of repositories. It is
4729 this for ad-hoc sharing and browsing of repositories. It is
4730 recommended to use a real web server to serve a repository for
4730 recommended to use a real web server to serve a repository for
4731 longer periods of time.
4731 longer periods of time.
4732
4732
4733 Please note that the server does not implement access control.
4733 Please note that the server does not implement access control.
4734 This means that, by default, anybody can read from the server and
4734 This means that, by default, anybody can read from the server and
4735 nobody can write to it by default. Set the ``web.allow-push``
4735 nobody can write to it by default. Set the ``web.allow-push``
4736 option to ``*`` to allow everybody to push to the server. You
4736 option to ``*`` to allow everybody to push to the server. You
4737 should use a real web server if you need to authenticate users.
4737 should use a real web server if you need to authenticate users.
4738
4738
4739 By default, the server logs accesses to stdout and errors to
4739 By default, the server logs accesses to stdout and errors to
4740 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4740 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4741 files.
4741 files.
4742
4742
4743 To have the server choose a free port number to listen on, specify
4743 To have the server choose a free port number to listen on, specify
4744 a port number of 0; in this case, the server will print the port
4744 a port number of 0; in this case, the server will print the port
4745 number it uses.
4745 number it uses.
4746
4746
4747 Returns 0 on success.
4747 Returns 0 on success.
4748 """
4748 """
4749
4749
4750 opts = pycompat.byteskwargs(opts)
4750 opts = pycompat.byteskwargs(opts)
4751 if opts["stdio"] and opts["cmdserver"]:
4751 if opts["stdio"] and opts["cmdserver"]:
4752 raise error.Abort(_("cannot use --stdio with --cmdserver"))
4752 raise error.Abort(_("cannot use --stdio with --cmdserver"))
4753
4753
4754 if opts["stdio"]:
4754 if opts["stdio"]:
4755 if repo is None:
4755 if repo is None:
4756 raise error.RepoError(_("there is no Mercurial repository here"
4756 raise error.RepoError(_("there is no Mercurial repository here"
4757 " (.hg not found)"))
4757 " (.hg not found)"))
4758 s = wireprotoserver.sshserver(ui, repo)
4758 s = wireprotoserver.sshserver(ui, repo)
4759 s.serve_forever()
4759 s.serve_forever()
4760
4760
4761 service = server.createservice(ui, repo, opts)
4761 service = server.createservice(ui, repo, opts)
4762 return server.runservice(opts, initfn=service.init, runfn=service.run)
4762 return server.runservice(opts, initfn=service.init, runfn=service.run)
4763
4763
4764 @command('^status|st',
4764 @command('^status|st',
4765 [('A', 'all', None, _('show status of all files')),
4765 [('A', 'all', None, _('show status of all files')),
4766 ('m', 'modified', None, _('show only modified files')),
4766 ('m', 'modified', None, _('show only modified files')),
4767 ('a', 'added', None, _('show only added files')),
4767 ('a', 'added', None, _('show only added files')),
4768 ('r', 'removed', None, _('show only removed files')),
4768 ('r', 'removed', None, _('show only removed files')),
4769 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4769 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4770 ('c', 'clean', None, _('show only files without changes')),
4770 ('c', 'clean', None, _('show only files without changes')),
4771 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4771 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4772 ('i', 'ignored', None, _('show only ignored files')),
4772 ('i', 'ignored', None, _('show only ignored files')),
4773 ('n', 'no-status', None, _('hide status prefix')),
4773 ('n', 'no-status', None, _('hide status prefix')),
4774 ('t', 'terse', '', _('show the terse output (EXPERIMENTAL)')),
4774 ('t', 'terse', '', _('show the terse output (EXPERIMENTAL)')),
4775 ('C', 'copies', None, _('show source of copied files')),
4775 ('C', 'copies', None, _('show source of copied files')),
4776 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4776 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4777 ('', 'rev', [], _('show difference from revision'), _('REV')),
4777 ('', 'rev', [], _('show difference from revision'), _('REV')),
4778 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4778 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4779 ] + walkopts + subrepoopts + formatteropts,
4779 ] + walkopts + subrepoopts + formatteropts,
4780 _('[OPTION]... [FILE]...'),
4780 _('[OPTION]... [FILE]...'),
4781 inferrepo=True, cmdtype=readonly)
4781 inferrepo=True, cmdtype=readonly)
4782 def status(ui, repo, *pats, **opts):
4782 def status(ui, repo, *pats, **opts):
4783 """show changed files in the working directory
4783 """show changed files in the working directory
4784
4784
4785 Show status of files in the repository. If names are given, only
4785 Show status of files in the repository. If names are given, only
4786 files that match are shown. Files that are clean or ignored or
4786 files that match are shown. Files that are clean or ignored or
4787 the source of a copy/move operation, are not listed unless
4787 the source of a copy/move operation, are not listed unless
4788 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4788 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4789 Unless options described with "show only ..." are given, the
4789 Unless options described with "show only ..." are given, the
4790 options -mardu are used.
4790 options -mardu are used.
4791
4791
4792 Option -q/--quiet hides untracked (unknown and ignored) files
4792 Option -q/--quiet hides untracked (unknown and ignored) files
4793 unless explicitly requested with -u/--unknown or -i/--ignored.
4793 unless explicitly requested with -u/--unknown or -i/--ignored.
4794
4794
4795 .. note::
4795 .. note::
4796
4796
4797 :hg:`status` may appear to disagree with diff if permissions have
4797 :hg:`status` may appear to disagree with diff if permissions have
4798 changed or a merge has occurred. The standard diff format does
4798 changed or a merge has occurred. The standard diff format does
4799 not report permission changes and diff only reports changes
4799 not report permission changes and diff only reports changes
4800 relative to one merge parent.
4800 relative to one merge parent.
4801
4801
4802 If one revision is given, it is used as the base revision.
4802 If one revision is given, it is used as the base revision.
4803 If two revisions are given, the differences between them are
4803 If two revisions are given, the differences between them are
4804 shown. The --change option can also be used as a shortcut to list
4804 shown. The --change option can also be used as a shortcut to list
4805 the changed files of a revision from its first parent.
4805 the changed files of a revision from its first parent.
4806
4806
4807 The codes used to show the status of files are::
4807 The codes used to show the status of files are::
4808
4808
4809 M = modified
4809 M = modified
4810 A = added
4810 A = added
4811 R = removed
4811 R = removed
4812 C = clean
4812 C = clean
4813 ! = missing (deleted by non-hg command, but still tracked)
4813 ! = missing (deleted by non-hg command, but still tracked)
4814 ? = not tracked
4814 ? = not tracked
4815 I = ignored
4815 I = ignored
4816 = origin of the previous file (with --copies)
4816 = origin of the previous file (with --copies)
4817
4817
4818 .. container:: verbose
4818 .. container:: verbose
4819
4819
4820 The -t/--terse option abbreviates the output by showing only the directory
4820 The -t/--terse option abbreviates the output by showing only the directory
4821 name if all the files in it share the same status. The option takes an
4821 name if all the files in it share the same status. The option takes an
4822 argument indicating the statuses to abbreviate: 'm' for 'modified', 'a'
4822 argument indicating the statuses to abbreviate: 'm' for 'modified', 'a'
4823 for 'added', 'r' for 'removed', 'd' for 'deleted', 'u' for 'unknown', 'i'
4823 for 'added', 'r' for 'removed', 'd' for 'deleted', 'u' for 'unknown', 'i'
4824 for 'ignored' and 'c' for clean.
4824 for 'ignored' and 'c' for clean.
4825
4825
4826 It abbreviates only those statuses which are passed. Note that clean and
4826 It abbreviates only those statuses which are passed. Note that clean and
4827 ignored files are not displayed with '--terse ic' unless the -c/--clean
4827 ignored files are not displayed with '--terse ic' unless the -c/--clean
4828 and -i/--ignored options are also used.
4828 and -i/--ignored options are also used.
4829
4829
4830 The -v/--verbose option shows information when the repository is in an
4830 The -v/--verbose option shows information when the repository is in an
4831 unfinished merge, shelve, rebase state etc. You can have this behavior
4831 unfinished merge, shelve, rebase state etc. You can have this behavior
4832 turned on by default by enabling the ``commands.status.verbose`` option.
4832 turned on by default by enabling the ``commands.status.verbose`` option.
4833
4833
4834 You can skip displaying some of these states by setting
4834 You can skip displaying some of these states by setting
4835 ``commands.status.skipstates`` to one or more of: 'bisect', 'graft',
4835 ``commands.status.skipstates`` to one or more of: 'bisect', 'graft',
4836 'histedit', 'merge', 'rebase', or 'unshelve'.
4836 'histedit', 'merge', 'rebase', or 'unshelve'.
4837
4837
4838 Examples:
4838 Examples:
4839
4839
4840 - show changes in the working directory relative to a
4840 - show changes in the working directory relative to a
4841 changeset::
4841 changeset::
4842
4842
4843 hg status --rev 9353
4843 hg status --rev 9353
4844
4844
4845 - show changes in the working directory relative to the
4845 - show changes in the working directory relative to the
4846 current directory (see :hg:`help patterns` for more information)::
4846 current directory (see :hg:`help patterns` for more information)::
4847
4847
4848 hg status re:
4848 hg status re:
4849
4849
4850 - show all changes including copies in an existing changeset::
4850 - show all changes including copies in an existing changeset::
4851
4851
4852 hg status --copies --change 9353
4852 hg status --copies --change 9353
4853
4853
4854 - get a NUL separated list of added files, suitable for xargs::
4854 - get a NUL separated list of added files, suitable for xargs::
4855
4855
4856 hg status -an0
4856 hg status -an0
4857
4857
4858 - show more information about the repository status, abbreviating
4858 - show more information about the repository status, abbreviating
4859 added, removed, modified, deleted, and untracked paths::
4859 added, removed, modified, deleted, and untracked paths::
4860
4860
4861 hg status -v -t mardu
4861 hg status -v -t mardu
4862
4862
4863 Returns 0 on success.
4863 Returns 0 on success.
4864
4864
4865 """
4865 """
4866
4866
4867 opts = pycompat.byteskwargs(opts)
4867 opts = pycompat.byteskwargs(opts)
4868 revs = opts.get('rev')
4868 revs = opts.get('rev')
4869 change = opts.get('change')
4869 change = opts.get('change')
4870 terse = opts.get('terse')
4870 terse = opts.get('terse')
4871
4871
4872 if revs and change:
4872 if revs and change:
4873 msg = _('cannot specify --rev and --change at the same time')
4873 msg = _('cannot specify --rev and --change at the same time')
4874 raise error.Abort(msg)
4874 raise error.Abort(msg)
4875 elif revs and terse:
4875 elif revs and terse:
4876 msg = _('cannot use --terse with --rev')
4876 msg = _('cannot use --terse with --rev')
4877 raise error.Abort(msg)
4877 raise error.Abort(msg)
4878 elif change:
4878 elif change:
4879 repo = scmutil.unhidehashlikerevs(repo, [change], 'nowarn')
4879 repo = scmutil.unhidehashlikerevs(repo, [change], 'nowarn')
4880 ctx2 = scmutil.revsingle(repo, change, None)
4880 ctx2 = scmutil.revsingle(repo, change, None)
4881 ctx1 = ctx2.p1()
4881 ctx1 = ctx2.p1()
4882 else:
4882 else:
4883 repo = scmutil.unhidehashlikerevs(repo, revs, 'nowarn')
4883 repo = scmutil.unhidehashlikerevs(repo, revs, 'nowarn')
4884 ctx1, ctx2 = scmutil.revpair(repo, revs)
4884 ctx1, ctx2 = scmutil.revpair(repo, revs)
4885
4885
4886 if pats or ui.configbool('commands', 'status.relative'):
4886 if pats or ui.configbool('commands', 'status.relative'):
4887 cwd = repo.getcwd()
4887 cwd = repo.getcwd()
4888 else:
4888 else:
4889 cwd = ''
4889 cwd = ''
4890
4890
4891 if opts.get('print0'):
4891 if opts.get('print0'):
4892 end = '\0'
4892 end = '\0'
4893 else:
4893 else:
4894 end = '\n'
4894 end = '\n'
4895 copy = {}
4895 copy = {}
4896 states = 'modified added removed deleted unknown ignored clean'.split()
4896 states = 'modified added removed deleted unknown ignored clean'.split()
4897 show = [k for k in states if opts.get(k)]
4897 show = [k for k in states if opts.get(k)]
4898 if opts.get('all'):
4898 if opts.get('all'):
4899 show += ui.quiet and (states[:4] + ['clean']) or states
4899 show += ui.quiet and (states[:4] + ['clean']) or states
4900
4900
4901 if not show:
4901 if not show:
4902 if ui.quiet:
4902 if ui.quiet:
4903 show = states[:4]
4903 show = states[:4]
4904 else:
4904 else:
4905 show = states[:5]
4905 show = states[:5]
4906
4906
4907 m = scmutil.match(ctx2, pats, opts)
4907 m = scmutil.match(ctx2, pats, opts)
4908 if terse:
4908 if terse:
4909 # we need to compute clean and unknown to terse
4909 # we need to compute clean and unknown to terse
4910 stat = repo.status(ctx1.node(), ctx2.node(), m,
4910 stat = repo.status(ctx1.node(), ctx2.node(), m,
4911 'ignored' in show or 'i' in terse,
4911 'ignored' in show or 'i' in terse,
4912 True, True, opts.get('subrepos'))
4912 True, True, opts.get('subrepos'))
4913
4913
4914 stat = cmdutil.tersedir(stat, terse)
4914 stat = cmdutil.tersedir(stat, terse)
4915 else:
4915 else:
4916 stat = repo.status(ctx1.node(), ctx2.node(), m,
4916 stat = repo.status(ctx1.node(), ctx2.node(), m,
4917 'ignored' in show, 'clean' in show,
4917 'ignored' in show, 'clean' in show,
4918 'unknown' in show, opts.get('subrepos'))
4918 'unknown' in show, opts.get('subrepos'))
4919
4919
4920 changestates = zip(states, pycompat.iterbytestr('MAR!?IC'), stat)
4920 changestates = zip(states, pycompat.iterbytestr('MAR!?IC'), stat)
4921
4921
4922 if (opts.get('all') or opts.get('copies')
4922 if (opts.get('all') or opts.get('copies')
4923 or ui.configbool('ui', 'statuscopies')) and not opts.get('no_status'):
4923 or ui.configbool('ui', 'statuscopies')) and not opts.get('no_status'):
4924 copy = copies.pathcopies(ctx1, ctx2, m)
4924 copy = copies.pathcopies(ctx1, ctx2, m)
4925
4925
4926 ui.pager('status')
4926 ui.pager('status')
4927 fm = ui.formatter('status', opts)
4927 fm = ui.formatter('status', opts)
4928 fmt = '%s' + end
4928 fmt = '%s' + end
4929 showchar = not opts.get('no_status')
4929 showchar = not opts.get('no_status')
4930
4930
4931 for state, char, files in changestates:
4931 for state, char, files in changestates:
4932 if state in show:
4932 if state in show:
4933 label = 'status.' + state
4933 label = 'status.' + state
4934 for f in files:
4934 for f in files:
4935 fm.startitem()
4935 fm.startitem()
4936 fm.condwrite(showchar, 'status', '%s ', char, label=label)
4936 fm.condwrite(showchar, 'status', '%s ', char, label=label)
4937 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
4937 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
4938 if f in copy:
4938 if f in copy:
4939 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
4939 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
4940 label='status.copied')
4940 label='status.copied')
4941
4941
4942 if ((ui.verbose or ui.configbool('commands', 'status.verbose'))
4942 if ((ui.verbose or ui.configbool('commands', 'status.verbose'))
4943 and not ui.plain()):
4943 and not ui.plain()):
4944 cmdutil.morestatus(repo, fm)
4944 cmdutil.morestatus(repo, fm)
4945 fm.end()
4945 fm.end()
4946
4946
4947 @command('^summary|sum',
4947 @command('^summary|sum',
4948 [('', 'remote', None, _('check for push and pull'))],
4948 [('', 'remote', None, _('check for push and pull'))],
4949 '[--remote]', cmdtype=readonly)
4949 '[--remote]', cmdtype=readonly)
4950 def summary(ui, repo, **opts):
4950 def summary(ui, repo, **opts):
4951 """summarize working directory state
4951 """summarize working directory state
4952
4952
4953 This generates a brief summary of the working directory state,
4953 This generates a brief summary of the working directory state,
4954 including parents, branch, commit status, phase and available updates.
4954 including parents, branch, commit status, phase and available updates.
4955
4955
4956 With the --remote option, this will check the default paths for
4956 With the --remote option, this will check the default paths for
4957 incoming and outgoing changes. This can be time-consuming.
4957 incoming and outgoing changes. This can be time-consuming.
4958
4958
4959 Returns 0 on success.
4959 Returns 0 on success.
4960 """
4960 """
4961
4961
4962 opts = pycompat.byteskwargs(opts)
4962 opts = pycompat.byteskwargs(opts)
4963 ui.pager('summary')
4963 ui.pager('summary')
4964 ctx = repo[None]
4964 ctx = repo[None]
4965 parents = ctx.parents()
4965 parents = ctx.parents()
4966 pnode = parents[0].node()
4966 pnode = parents[0].node()
4967 marks = []
4967 marks = []
4968
4968
4969 ms = None
4969 ms = None
4970 try:
4970 try:
4971 ms = mergemod.mergestate.read(repo)
4971 ms = mergemod.mergestate.read(repo)
4972 except error.UnsupportedMergeRecords as e:
4972 except error.UnsupportedMergeRecords as e:
4973 s = ' '.join(e.recordtypes)
4973 s = ' '.join(e.recordtypes)
4974 ui.warn(
4974 ui.warn(
4975 _('warning: merge state has unsupported record types: %s\n') % s)
4975 _('warning: merge state has unsupported record types: %s\n') % s)
4976 unresolved = []
4976 unresolved = []
4977 else:
4977 else:
4978 unresolved = list(ms.unresolved())
4978 unresolved = list(ms.unresolved())
4979
4979
4980 for p in parents:
4980 for p in parents:
4981 # label with log.changeset (instead of log.parent) since this
4981 # label with log.changeset (instead of log.parent) since this
4982 # shows a working directory parent *changeset*:
4982 # shows a working directory parent *changeset*:
4983 # i18n: column positioning for "hg summary"
4983 # i18n: column positioning for "hg summary"
4984 ui.write(_('parent: %d:%s ') % (p.rev(), p),
4984 ui.write(_('parent: %d:%s ') % (p.rev(), p),
4985 label=logcmdutil.changesetlabels(p))
4985 label=logcmdutil.changesetlabels(p))
4986 ui.write(' '.join(p.tags()), label='log.tag')
4986 ui.write(' '.join(p.tags()), label='log.tag')
4987 if p.bookmarks():
4987 if p.bookmarks():
4988 marks.extend(p.bookmarks())
4988 marks.extend(p.bookmarks())
4989 if p.rev() == -1:
4989 if p.rev() == -1:
4990 if not len(repo):
4990 if not len(repo):
4991 ui.write(_(' (empty repository)'))
4991 ui.write(_(' (empty repository)'))
4992 else:
4992 else:
4993 ui.write(_(' (no revision checked out)'))
4993 ui.write(_(' (no revision checked out)'))
4994 if p.obsolete():
4994 if p.obsolete():
4995 ui.write(_(' (obsolete)'))
4995 ui.write(_(' (obsolete)'))
4996 if p.isunstable():
4996 if p.isunstable():
4997 instabilities = (ui.label(instability, 'trouble.%s' % instability)
4997 instabilities = (ui.label(instability, 'trouble.%s' % instability)
4998 for instability in p.instabilities())
4998 for instability in p.instabilities())
4999 ui.write(' ('
4999 ui.write(' ('
5000 + ', '.join(instabilities)
5000 + ', '.join(instabilities)
5001 + ')')
5001 + ')')
5002 ui.write('\n')
5002 ui.write('\n')
5003 if p.description():
5003 if p.description():
5004 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5004 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5005 label='log.summary')
5005 label='log.summary')
5006
5006
5007 branch = ctx.branch()
5007 branch = ctx.branch()
5008 bheads = repo.branchheads(branch)
5008 bheads = repo.branchheads(branch)
5009 # i18n: column positioning for "hg summary"
5009 # i18n: column positioning for "hg summary"
5010 m = _('branch: %s\n') % branch
5010 m = _('branch: %s\n') % branch
5011 if branch != 'default':
5011 if branch != 'default':
5012 ui.write(m, label='log.branch')
5012 ui.write(m, label='log.branch')
5013 else:
5013 else:
5014 ui.status(m, label='log.branch')
5014 ui.status(m, label='log.branch')
5015
5015
5016 if marks:
5016 if marks:
5017 active = repo._activebookmark
5017 active = repo._activebookmark
5018 # i18n: column positioning for "hg summary"
5018 # i18n: column positioning for "hg summary"
5019 ui.write(_('bookmarks:'), label='log.bookmark')
5019 ui.write(_('bookmarks:'), label='log.bookmark')
5020 if active is not None:
5020 if active is not None:
5021 if active in marks:
5021 if active in marks:
5022 ui.write(' *' + active, label=bookmarks.activebookmarklabel)
5022 ui.write(' *' + active, label=bookmarks.activebookmarklabel)
5023 marks.remove(active)
5023 marks.remove(active)
5024 else:
5024 else:
5025 ui.write(' [%s]' % active, label=bookmarks.activebookmarklabel)
5025 ui.write(' [%s]' % active, label=bookmarks.activebookmarklabel)
5026 for m in marks:
5026 for m in marks:
5027 ui.write(' ' + m, label='log.bookmark')
5027 ui.write(' ' + m, label='log.bookmark')
5028 ui.write('\n', label='log.bookmark')
5028 ui.write('\n', label='log.bookmark')
5029
5029
5030 status = repo.status(unknown=True)
5030 status = repo.status(unknown=True)
5031
5031
5032 c = repo.dirstate.copies()
5032 c = repo.dirstate.copies()
5033 copied, renamed = [], []
5033 copied, renamed = [], []
5034 for d, s in c.iteritems():
5034 for d, s in c.iteritems():
5035 if s in status.removed:
5035 if s in status.removed:
5036 status.removed.remove(s)
5036 status.removed.remove(s)
5037 renamed.append(d)
5037 renamed.append(d)
5038 else:
5038 else:
5039 copied.append(d)
5039 copied.append(d)
5040 if d in status.added:
5040 if d in status.added:
5041 status.added.remove(d)
5041 status.added.remove(d)
5042
5042
5043 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5043 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5044
5044
5045 labels = [(ui.label(_('%d modified'), 'status.modified'), status.modified),
5045 labels = [(ui.label(_('%d modified'), 'status.modified'), status.modified),
5046 (ui.label(_('%d added'), 'status.added'), status.added),
5046 (ui.label(_('%d added'), 'status.added'), status.added),
5047 (ui.label(_('%d removed'), 'status.removed'), status.removed),
5047 (ui.label(_('%d removed'), 'status.removed'), status.removed),
5048 (ui.label(_('%d renamed'), 'status.copied'), renamed),
5048 (ui.label(_('%d renamed'), 'status.copied'), renamed),
5049 (ui.label(_('%d copied'), 'status.copied'), copied),
5049 (ui.label(_('%d copied'), 'status.copied'), copied),
5050 (ui.label(_('%d deleted'), 'status.deleted'), status.deleted),
5050 (ui.label(_('%d deleted'), 'status.deleted'), status.deleted),
5051 (ui.label(_('%d unknown'), 'status.unknown'), status.unknown),
5051 (ui.label(_('%d unknown'), 'status.unknown'), status.unknown),
5052 (ui.label(_('%d unresolved'), 'resolve.unresolved'), unresolved),
5052 (ui.label(_('%d unresolved'), 'resolve.unresolved'), unresolved),
5053 (ui.label(_('%d subrepos'), 'status.modified'), subs)]
5053 (ui.label(_('%d subrepos'), 'status.modified'), subs)]
5054 t = []
5054 t = []
5055 for l, s in labels:
5055 for l, s in labels:
5056 if s:
5056 if s:
5057 t.append(l % len(s))
5057 t.append(l % len(s))
5058
5058
5059 t = ', '.join(t)
5059 t = ', '.join(t)
5060 cleanworkdir = False
5060 cleanworkdir = False
5061
5061
5062 if repo.vfs.exists('graftstate'):
5062 if repo.vfs.exists('graftstate'):
5063 t += _(' (graft in progress)')
5063 t += _(' (graft in progress)')
5064 if repo.vfs.exists('updatestate'):
5064 if repo.vfs.exists('updatestate'):
5065 t += _(' (interrupted update)')
5065 t += _(' (interrupted update)')
5066 elif len(parents) > 1:
5066 elif len(parents) > 1:
5067 t += _(' (merge)')
5067 t += _(' (merge)')
5068 elif branch != parents[0].branch():
5068 elif branch != parents[0].branch():
5069 t += _(' (new branch)')
5069 t += _(' (new branch)')
5070 elif (parents[0].closesbranch() and
5070 elif (parents[0].closesbranch() and
5071 pnode in repo.branchheads(branch, closed=True)):
5071 pnode in repo.branchheads(branch, closed=True)):
5072 t += _(' (head closed)')
5072 t += _(' (head closed)')
5073 elif not (status.modified or status.added or status.removed or renamed or
5073 elif not (status.modified or status.added or status.removed or renamed or
5074 copied or subs):
5074 copied or subs):
5075 t += _(' (clean)')
5075 t += _(' (clean)')
5076 cleanworkdir = True
5076 cleanworkdir = True
5077 elif pnode not in bheads:
5077 elif pnode not in bheads:
5078 t += _(' (new branch head)')
5078 t += _(' (new branch head)')
5079
5079
5080 if parents:
5080 if parents:
5081 pendingphase = max(p.phase() for p in parents)
5081 pendingphase = max(p.phase() for p in parents)
5082 else:
5082 else:
5083 pendingphase = phases.public
5083 pendingphase = phases.public
5084
5084
5085 if pendingphase > phases.newcommitphase(ui):
5085 if pendingphase > phases.newcommitphase(ui):
5086 t += ' (%s)' % phases.phasenames[pendingphase]
5086 t += ' (%s)' % phases.phasenames[pendingphase]
5087
5087
5088 if cleanworkdir:
5088 if cleanworkdir:
5089 # i18n: column positioning for "hg summary"
5089 # i18n: column positioning for "hg summary"
5090 ui.status(_('commit: %s\n') % t.strip())
5090 ui.status(_('commit: %s\n') % t.strip())
5091 else:
5091 else:
5092 # i18n: column positioning for "hg summary"
5092 # i18n: column positioning for "hg summary"
5093 ui.write(_('commit: %s\n') % t.strip())
5093 ui.write(_('commit: %s\n') % t.strip())
5094
5094
5095 # all ancestors of branch heads - all ancestors of parent = new csets
5095 # all ancestors of branch heads - all ancestors of parent = new csets
5096 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
5096 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
5097 bheads))
5097 bheads))
5098
5098
5099 if new == 0:
5099 if new == 0:
5100 # i18n: column positioning for "hg summary"
5100 # i18n: column positioning for "hg summary"
5101 ui.status(_('update: (current)\n'))
5101 ui.status(_('update: (current)\n'))
5102 elif pnode not in bheads:
5102 elif pnode not in bheads:
5103 # i18n: column positioning for "hg summary"
5103 # i18n: column positioning for "hg summary"
5104 ui.write(_('update: %d new changesets (update)\n') % new)
5104 ui.write(_('update: %d new changesets (update)\n') % new)
5105 else:
5105 else:
5106 # i18n: column positioning for "hg summary"
5106 # i18n: column positioning for "hg summary"
5107 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5107 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5108 (new, len(bheads)))
5108 (new, len(bheads)))
5109
5109
5110 t = []
5110 t = []
5111 draft = len(repo.revs('draft()'))
5111 draft = len(repo.revs('draft()'))
5112 if draft:
5112 if draft:
5113 t.append(_('%d draft') % draft)
5113 t.append(_('%d draft') % draft)
5114 secret = len(repo.revs('secret()'))
5114 secret = len(repo.revs('secret()'))
5115 if secret:
5115 if secret:
5116 t.append(_('%d secret') % secret)
5116 t.append(_('%d secret') % secret)
5117
5117
5118 if draft or secret:
5118 if draft or secret:
5119 ui.status(_('phases: %s\n') % ', '.join(t))
5119 ui.status(_('phases: %s\n') % ', '.join(t))
5120
5120
5121 if obsolete.isenabled(repo, obsolete.createmarkersopt):
5121 if obsolete.isenabled(repo, obsolete.createmarkersopt):
5122 for trouble in ("orphan", "contentdivergent", "phasedivergent"):
5122 for trouble in ("orphan", "contentdivergent", "phasedivergent"):
5123 numtrouble = len(repo.revs(trouble + "()"))
5123 numtrouble = len(repo.revs(trouble + "()"))
5124 # We write all the possibilities to ease translation
5124 # We write all the possibilities to ease translation
5125 troublemsg = {
5125 troublemsg = {
5126 "orphan": _("orphan: %d changesets"),
5126 "orphan": _("orphan: %d changesets"),
5127 "contentdivergent": _("content-divergent: %d changesets"),
5127 "contentdivergent": _("content-divergent: %d changesets"),
5128 "phasedivergent": _("phase-divergent: %d changesets"),
5128 "phasedivergent": _("phase-divergent: %d changesets"),
5129 }
5129 }
5130 if numtrouble > 0:
5130 if numtrouble > 0:
5131 ui.status(troublemsg[trouble] % numtrouble + "\n")
5131 ui.status(troublemsg[trouble] % numtrouble + "\n")
5132
5132
5133 cmdutil.summaryhooks(ui, repo)
5133 cmdutil.summaryhooks(ui, repo)
5134
5134
5135 if opts.get('remote'):
5135 if opts.get('remote'):
5136 needsincoming, needsoutgoing = True, True
5136 needsincoming, needsoutgoing = True, True
5137 else:
5137 else:
5138 needsincoming, needsoutgoing = False, False
5138 needsincoming, needsoutgoing = False, False
5139 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
5139 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
5140 if i:
5140 if i:
5141 needsincoming = True
5141 needsincoming = True
5142 if o:
5142 if o:
5143 needsoutgoing = True
5143 needsoutgoing = True
5144 if not needsincoming and not needsoutgoing:
5144 if not needsincoming and not needsoutgoing:
5145 return
5145 return
5146
5146
5147 def getincoming():
5147 def getincoming():
5148 source, branches = hg.parseurl(ui.expandpath('default'))
5148 source, branches = hg.parseurl(ui.expandpath('default'))
5149 sbranch = branches[0]
5149 sbranch = branches[0]
5150 try:
5150 try:
5151 other = hg.peer(repo, {}, source)
5151 other = hg.peer(repo, {}, source)
5152 except error.RepoError:
5152 except error.RepoError:
5153 if opts.get('remote'):
5153 if opts.get('remote'):
5154 raise
5154 raise
5155 return source, sbranch, None, None, None
5155 return source, sbranch, None, None, None
5156 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5156 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5157 if revs:
5157 if revs:
5158 revs = [other.lookup(rev) for rev in revs]
5158 revs = [other.lookup(rev) for rev in revs]
5159 ui.debug('comparing with %s\n' % util.hidepassword(source))
5159 ui.debug('comparing with %s\n' % util.hidepassword(source))
5160 repo.ui.pushbuffer()
5160 repo.ui.pushbuffer()
5161 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5161 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5162 repo.ui.popbuffer()
5162 repo.ui.popbuffer()
5163 return source, sbranch, other, commoninc, commoninc[1]
5163 return source, sbranch, other, commoninc, commoninc[1]
5164
5164
5165 if needsincoming:
5165 if needsincoming:
5166 source, sbranch, sother, commoninc, incoming = getincoming()
5166 source, sbranch, sother, commoninc, incoming = getincoming()
5167 else:
5167 else:
5168 source = sbranch = sother = commoninc = incoming = None
5168 source = sbranch = sother = commoninc = incoming = None
5169
5169
5170 def getoutgoing():
5170 def getoutgoing():
5171 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5171 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5172 dbranch = branches[0]
5172 dbranch = branches[0]
5173 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5173 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5174 if source != dest:
5174 if source != dest:
5175 try:
5175 try:
5176 dother = hg.peer(repo, {}, dest)
5176 dother = hg.peer(repo, {}, dest)
5177 except error.RepoError:
5177 except error.RepoError:
5178 if opts.get('remote'):
5178 if opts.get('remote'):
5179 raise
5179 raise
5180 return dest, dbranch, None, None
5180 return dest, dbranch, None, None
5181 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5181 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5182 elif sother is None:
5182 elif sother is None:
5183 # there is no explicit destination peer, but source one is invalid
5183 # there is no explicit destination peer, but source one is invalid
5184 return dest, dbranch, None, None
5184 return dest, dbranch, None, None
5185 else:
5185 else:
5186 dother = sother
5186 dother = sother
5187 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5187 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5188 common = None
5188 common = None
5189 else:
5189 else:
5190 common = commoninc
5190 common = commoninc
5191 if revs:
5191 if revs:
5192 revs = [repo.lookup(rev) for rev in revs]
5192 revs = [repo.lookup(rev) for rev in revs]
5193 repo.ui.pushbuffer()
5193 repo.ui.pushbuffer()
5194 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
5194 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
5195 commoninc=common)
5195 commoninc=common)
5196 repo.ui.popbuffer()
5196 repo.ui.popbuffer()
5197 return dest, dbranch, dother, outgoing
5197 return dest, dbranch, dother, outgoing
5198
5198
5199 if needsoutgoing:
5199 if needsoutgoing:
5200 dest, dbranch, dother, outgoing = getoutgoing()
5200 dest, dbranch, dother, outgoing = getoutgoing()
5201 else:
5201 else:
5202 dest = dbranch = dother = outgoing = None
5202 dest = dbranch = dother = outgoing = None
5203
5203
5204 if opts.get('remote'):
5204 if opts.get('remote'):
5205 t = []
5205 t = []
5206 if incoming:
5206 if incoming:
5207 t.append(_('1 or more incoming'))
5207 t.append(_('1 or more incoming'))
5208 o = outgoing.missing
5208 o = outgoing.missing
5209 if o:
5209 if o:
5210 t.append(_('%d outgoing') % len(o))
5210 t.append(_('%d outgoing') % len(o))
5211 other = dother or sother
5211 other = dother or sother
5212 if 'bookmarks' in other.listkeys('namespaces'):
5212 if 'bookmarks' in other.listkeys('namespaces'):
5213 counts = bookmarks.summary(repo, other)
5213 counts = bookmarks.summary(repo, other)
5214 if counts[0] > 0:
5214 if counts[0] > 0:
5215 t.append(_('%d incoming bookmarks') % counts[0])
5215 t.append(_('%d incoming bookmarks') % counts[0])
5216 if counts[1] > 0:
5216 if counts[1] > 0:
5217 t.append(_('%d outgoing bookmarks') % counts[1])
5217 t.append(_('%d outgoing bookmarks') % counts[1])
5218
5218
5219 if t:
5219 if t:
5220 # i18n: column positioning for "hg summary"
5220 # i18n: column positioning for "hg summary"
5221 ui.write(_('remote: %s\n') % (', '.join(t)))
5221 ui.write(_('remote: %s\n') % (', '.join(t)))
5222 else:
5222 else:
5223 # i18n: column positioning for "hg summary"
5223 # i18n: column positioning for "hg summary"
5224 ui.status(_('remote: (synced)\n'))
5224 ui.status(_('remote: (synced)\n'))
5225
5225
5226 cmdutil.summaryremotehooks(ui, repo, opts,
5226 cmdutil.summaryremotehooks(ui, repo, opts,
5227 ((source, sbranch, sother, commoninc),
5227 ((source, sbranch, sother, commoninc),
5228 (dest, dbranch, dother, outgoing)))
5228 (dest, dbranch, dother, outgoing)))
5229
5229
5230 @command('tag',
5230 @command('tag',
5231 [('f', 'force', None, _('force tag')),
5231 [('f', 'force', None, _('force tag')),
5232 ('l', 'local', None, _('make the tag local')),
5232 ('l', 'local', None, _('make the tag local')),
5233 ('r', 'rev', '', _('revision to tag'), _('REV')),
5233 ('r', 'rev', '', _('revision to tag'), _('REV')),
5234 ('', 'remove', None, _('remove a tag')),
5234 ('', 'remove', None, _('remove a tag')),
5235 # -l/--local is already there, commitopts cannot be used
5235 # -l/--local is already there, commitopts cannot be used
5236 ('e', 'edit', None, _('invoke editor on commit messages')),
5236 ('e', 'edit', None, _('invoke editor on commit messages')),
5237 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
5237 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
5238 ] + commitopts2,
5238 ] + commitopts2,
5239 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5239 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5240 def tag(ui, repo, name1, *names, **opts):
5240 def tag(ui, repo, name1, *names, **opts):
5241 """add one or more tags for the current or given revision
5241 """add one or more tags for the current or given revision
5242
5242
5243 Name a particular revision using <name>.
5243 Name a particular revision using <name>.
5244
5244
5245 Tags are used to name particular revisions of the repository and are
5245 Tags are used to name particular revisions of the repository and are
5246 very useful to compare different revisions, to go back to significant
5246 very useful to compare different revisions, to go back to significant
5247 earlier versions or to mark branch points as releases, etc. Changing
5247 earlier versions or to mark branch points as releases, etc. Changing
5248 an existing tag is normally disallowed; use -f/--force to override.
5248 an existing tag is normally disallowed; use -f/--force to override.
5249
5249
5250 If no revision is given, the parent of the working directory is
5250 If no revision is given, the parent of the working directory is
5251 used.
5251 used.
5252
5252
5253 To facilitate version control, distribution, and merging of tags,
5253 To facilitate version control, distribution, and merging of tags,
5254 they are stored as a file named ".hgtags" which is managed similarly
5254 they are stored as a file named ".hgtags" which is managed similarly
5255 to other project files and can be hand-edited if necessary. This
5255 to other project files and can be hand-edited if necessary. This
5256 also means that tagging creates a new commit. The file
5256 also means that tagging creates a new commit. The file
5257 ".hg/localtags" is used for local tags (not shared among
5257 ".hg/localtags" is used for local tags (not shared among
5258 repositories).
5258 repositories).
5259
5259
5260 Tag commits are usually made at the head of a branch. If the parent
5260 Tag commits are usually made at the head of a branch. If the parent
5261 of the working directory is not a branch head, :hg:`tag` aborts; use
5261 of the working directory is not a branch head, :hg:`tag` aborts; use
5262 -f/--force to force the tag commit to be based on a non-head
5262 -f/--force to force the tag commit to be based on a non-head
5263 changeset.
5263 changeset.
5264
5264
5265 See :hg:`help dates` for a list of formats valid for -d/--date.
5265 See :hg:`help dates` for a list of formats valid for -d/--date.
5266
5266
5267 Since tag names have priority over branch names during revision
5267 Since tag names have priority over branch names during revision
5268 lookup, using an existing branch name as a tag name is discouraged.
5268 lookup, using an existing branch name as a tag name is discouraged.
5269
5269
5270 Returns 0 on success.
5270 Returns 0 on success.
5271 """
5271 """
5272 opts = pycompat.byteskwargs(opts)
5272 opts = pycompat.byteskwargs(opts)
5273 wlock = lock = None
5273 wlock = lock = None
5274 try:
5274 try:
5275 wlock = repo.wlock()
5275 wlock = repo.wlock()
5276 lock = repo.lock()
5276 lock = repo.lock()
5277 rev_ = "."
5277 rev_ = "."
5278 names = [t.strip() for t in (name1,) + names]
5278 names = [t.strip() for t in (name1,) + names]
5279 if len(names) != len(set(names)):
5279 if len(names) != len(set(names)):
5280 raise error.Abort(_('tag names must be unique'))
5280 raise error.Abort(_('tag names must be unique'))
5281 for n in names:
5281 for n in names:
5282 scmutil.checknewlabel(repo, n, 'tag')
5282 scmutil.checknewlabel(repo, n, 'tag')
5283 if not n:
5283 if not n:
5284 raise error.Abort(_('tag names cannot consist entirely of '
5284 raise error.Abort(_('tag names cannot consist entirely of '
5285 'whitespace'))
5285 'whitespace'))
5286 if opts.get('rev') and opts.get('remove'):
5286 if opts.get('rev') and opts.get('remove'):
5287 raise error.Abort(_("--rev and --remove are incompatible"))
5287 raise error.Abort(_("--rev and --remove are incompatible"))
5288 if opts.get('rev'):
5288 if opts.get('rev'):
5289 rev_ = opts['rev']
5289 rev_ = opts['rev']
5290 message = opts.get('message')
5290 message = opts.get('message')
5291 if opts.get('remove'):
5291 if opts.get('remove'):
5292 if opts.get('local'):
5292 if opts.get('local'):
5293 expectedtype = 'local'
5293 expectedtype = 'local'
5294 else:
5294 else:
5295 expectedtype = 'global'
5295 expectedtype = 'global'
5296
5296
5297 for n in names:
5297 for n in names:
5298 if not repo.tagtype(n):
5298 if not repo.tagtype(n):
5299 raise error.Abort(_("tag '%s' does not exist") % n)
5299 raise error.Abort(_("tag '%s' does not exist") % n)
5300 if repo.tagtype(n) != expectedtype:
5300 if repo.tagtype(n) != expectedtype:
5301 if expectedtype == 'global':
5301 if expectedtype == 'global':
5302 raise error.Abort(_("tag '%s' is not a global tag") % n)
5302 raise error.Abort(_("tag '%s' is not a global tag") % n)
5303 else:
5303 else:
5304 raise error.Abort(_("tag '%s' is not a local tag") % n)
5304 raise error.Abort(_("tag '%s' is not a local tag") % n)
5305 rev_ = 'null'
5305 rev_ = 'null'
5306 if not message:
5306 if not message:
5307 # we don't translate commit messages
5307 # we don't translate commit messages
5308 message = 'Removed tag %s' % ', '.join(names)
5308 message = 'Removed tag %s' % ', '.join(names)
5309 elif not opts.get('force'):
5309 elif not opts.get('force'):
5310 for n in names:
5310 for n in names:
5311 if n in repo.tags():
5311 if n in repo.tags():
5312 raise error.Abort(_("tag '%s' already exists "
5312 raise error.Abort(_("tag '%s' already exists "
5313 "(use -f to force)") % n)
5313 "(use -f to force)") % n)
5314 if not opts.get('local'):
5314 if not opts.get('local'):
5315 p1, p2 = repo.dirstate.parents()
5315 p1, p2 = repo.dirstate.parents()
5316 if p2 != nullid:
5316 if p2 != nullid:
5317 raise error.Abort(_('uncommitted merge'))
5317 raise error.Abort(_('uncommitted merge'))
5318 bheads = repo.branchheads()
5318 bheads = repo.branchheads()
5319 if not opts.get('force') and bheads and p1 not in bheads:
5319 if not opts.get('force') and bheads and p1 not in bheads:
5320 raise error.Abort(_('working directory is not at a branch head '
5320 raise error.Abort(_('working directory is not at a branch head '
5321 '(use -f to force)'))
5321 '(use -f to force)'))
5322 node = scmutil.revsingle(repo, rev_).node()
5322 node = scmutil.revsingle(repo, rev_).node()
5323
5323
5324 if not message:
5324 if not message:
5325 # we don't translate commit messages
5325 # we don't translate commit messages
5326 message = ('Added tag %s for changeset %s' %
5326 message = ('Added tag %s for changeset %s' %
5327 (', '.join(names), short(node)))
5327 (', '.join(names), short(node)))
5328
5328
5329 date = opts.get('date')
5329 date = opts.get('date')
5330 if date:
5330 if date:
5331 date = dateutil.parsedate(date)
5331 date = dateutil.parsedate(date)
5332
5332
5333 if opts.get('remove'):
5333 if opts.get('remove'):
5334 editform = 'tag.remove'
5334 editform = 'tag.remove'
5335 else:
5335 else:
5336 editform = 'tag.add'
5336 editform = 'tag.add'
5337 editor = cmdutil.getcommiteditor(editform=editform,
5337 editor = cmdutil.getcommiteditor(editform=editform,
5338 **pycompat.strkwargs(opts))
5338 **pycompat.strkwargs(opts))
5339
5339
5340 # don't allow tagging the null rev
5340 # don't allow tagging the null rev
5341 if (not opts.get('remove') and
5341 if (not opts.get('remove') and
5342 scmutil.revsingle(repo, rev_).rev() == nullrev):
5342 scmutil.revsingle(repo, rev_).rev() == nullrev):
5343 raise error.Abort(_("cannot tag null revision"))
5343 raise error.Abort(_("cannot tag null revision"))
5344
5344
5345 tagsmod.tag(repo, names, node, message, opts.get('local'),
5345 tagsmod.tag(repo, names, node, message, opts.get('local'),
5346 opts.get('user'), date, editor=editor)
5346 opts.get('user'), date, editor=editor)
5347 finally:
5347 finally:
5348 release(lock, wlock)
5348 release(lock, wlock)
5349
5349
5350 @command('tags', formatteropts, '', cmdtype=readonly)
5350 @command('tags', formatteropts, '', cmdtype=readonly)
5351 def tags(ui, repo, **opts):
5351 def tags(ui, repo, **opts):
5352 """list repository tags
5352 """list repository tags
5353
5353
5354 This lists both regular and local tags. When the -v/--verbose
5354 This lists both regular and local tags. When the -v/--verbose
5355 switch is used, a third column "local" is printed for local tags.
5355 switch is used, a third column "local" is printed for local tags.
5356 When the -q/--quiet switch is used, only the tag name is printed.
5356 When the -q/--quiet switch is used, only the tag name is printed.
5357
5357
5358 Returns 0 on success.
5358 Returns 0 on success.
5359 """
5359 """
5360
5360
5361 opts = pycompat.byteskwargs(opts)
5361 opts = pycompat.byteskwargs(opts)
5362 ui.pager('tags')
5362 ui.pager('tags')
5363 fm = ui.formatter('tags', opts)
5363 fm = ui.formatter('tags', opts)
5364 hexfunc = fm.hexfunc
5364 hexfunc = fm.hexfunc
5365 tagtype = ""
5365 tagtype = ""
5366
5366
5367 for t, n in reversed(repo.tagslist()):
5367 for t, n in reversed(repo.tagslist()):
5368 hn = hexfunc(n)
5368 hn = hexfunc(n)
5369 label = 'tags.normal'
5369 label = 'tags.normal'
5370 tagtype = ''
5370 tagtype = ''
5371 if repo.tagtype(t) == 'local':
5371 if repo.tagtype(t) == 'local':
5372 label = 'tags.local'
5372 label = 'tags.local'
5373 tagtype = 'local'
5373 tagtype = 'local'
5374
5374
5375 fm.startitem()
5375 fm.startitem()
5376 fm.write('tag', '%s', t, label=label)
5376 fm.write('tag', '%s', t, label=label)
5377 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5377 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5378 fm.condwrite(not ui.quiet, 'rev node', fmt,
5378 fm.condwrite(not ui.quiet, 'rev node', fmt,
5379 repo.changelog.rev(n), hn, label=label)
5379 repo.changelog.rev(n), hn, label=label)
5380 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5380 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5381 tagtype, label=label)
5381 tagtype, label=label)
5382 fm.plain('\n')
5382 fm.plain('\n')
5383 fm.end()
5383 fm.end()
5384
5384
5385 @command('tip',
5385 @command('tip',
5386 [('p', 'patch', None, _('show patch')),
5386 [('p', 'patch', None, _('show patch')),
5387 ('g', 'git', None, _('use git extended diff format')),
5387 ('g', 'git', None, _('use git extended diff format')),
5388 ] + templateopts,
5388 ] + templateopts,
5389 _('[-p] [-g]'))
5389 _('[-p] [-g]'))
5390 def tip(ui, repo, **opts):
5390 def tip(ui, repo, **opts):
5391 """show the tip revision (DEPRECATED)
5391 """show the tip revision (DEPRECATED)
5392
5392
5393 The tip revision (usually just called the tip) is the changeset
5393 The tip revision (usually just called the tip) is the changeset
5394 most recently added to the repository (and therefore the most
5394 most recently added to the repository (and therefore the most
5395 recently changed head).
5395 recently changed head).
5396
5396
5397 If you have just made a commit, that commit will be the tip. If
5397 If you have just made a commit, that commit will be the tip. If
5398 you have just pulled changes from another repository, the tip of
5398 you have just pulled changes from another repository, the tip of
5399 that repository becomes the current tip. The "tip" tag is special
5399 that repository becomes the current tip. The "tip" tag is special
5400 and cannot be renamed or assigned to a different changeset.
5400 and cannot be renamed or assigned to a different changeset.
5401
5401
5402 This command is deprecated, please use :hg:`heads` instead.
5402 This command is deprecated, please use :hg:`heads` instead.
5403
5403
5404 Returns 0 on success.
5404 Returns 0 on success.
5405 """
5405 """
5406 opts = pycompat.byteskwargs(opts)
5406 opts = pycompat.byteskwargs(opts)
5407 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
5407 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
5408 displayer.show(repo['tip'])
5408 displayer.show(repo['tip'])
5409 displayer.close()
5409 displayer.close()
5410
5410
5411 @command('unbundle',
5411 @command('unbundle',
5412 [('u', 'update', None,
5412 [('u', 'update', None,
5413 _('update to new branch head if changesets were unbundled'))],
5413 _('update to new branch head if changesets were unbundled'))],
5414 _('[-u] FILE...'))
5414 _('[-u] FILE...'))
5415 def unbundle(ui, repo, fname1, *fnames, **opts):
5415 def unbundle(ui, repo, fname1, *fnames, **opts):
5416 """apply one or more bundle files
5416 """apply one or more bundle files
5417
5417
5418 Apply one or more bundle files generated by :hg:`bundle`.
5418 Apply one or more bundle files generated by :hg:`bundle`.
5419
5419
5420 Returns 0 on success, 1 if an update has unresolved files.
5420 Returns 0 on success, 1 if an update has unresolved files.
5421 """
5421 """
5422 fnames = (fname1,) + fnames
5422 fnames = (fname1,) + fnames
5423
5423
5424 with repo.lock():
5424 with repo.lock():
5425 for fname in fnames:
5425 for fname in fnames:
5426 f = hg.openpath(ui, fname)
5426 f = hg.openpath(ui, fname)
5427 gen = exchange.readbundle(ui, f, fname)
5427 gen = exchange.readbundle(ui, f, fname)
5428 if isinstance(gen, streamclone.streamcloneapplier):
5428 if isinstance(gen, streamclone.streamcloneapplier):
5429 raise error.Abort(
5429 raise error.Abort(
5430 _('packed bundles cannot be applied with '
5430 _('packed bundles cannot be applied with '
5431 '"hg unbundle"'),
5431 '"hg unbundle"'),
5432 hint=_('use "hg debugapplystreamclonebundle"'))
5432 hint=_('use "hg debugapplystreamclonebundle"'))
5433 url = 'bundle:' + fname
5433 url = 'bundle:' + fname
5434 try:
5434 try:
5435 txnname = 'unbundle'
5435 txnname = 'unbundle'
5436 if not isinstance(gen, bundle2.unbundle20):
5436 if not isinstance(gen, bundle2.unbundle20):
5437 txnname = 'unbundle\n%s' % util.hidepassword(url)
5437 txnname = 'unbundle\n%s' % util.hidepassword(url)
5438 with repo.transaction(txnname) as tr:
5438 with repo.transaction(txnname) as tr:
5439 op = bundle2.applybundle(repo, gen, tr, source='unbundle',
5439 op = bundle2.applybundle(repo, gen, tr, source='unbundle',
5440 url=url)
5440 url=url)
5441 except error.BundleUnknownFeatureError as exc:
5441 except error.BundleUnknownFeatureError as exc:
5442 raise error.Abort(
5442 raise error.Abort(
5443 _('%s: unknown bundle feature, %s') % (fname, exc),
5443 _('%s: unknown bundle feature, %s') % (fname, exc),
5444 hint=_("see https://mercurial-scm.org/"
5444 hint=_("see https://mercurial-scm.org/"
5445 "wiki/BundleFeature for more "
5445 "wiki/BundleFeature for more "
5446 "information"))
5446 "information"))
5447 modheads = bundle2.combinechangegroupresults(op)
5447 modheads = bundle2.combinechangegroupresults(op)
5448
5448
5449 return postincoming(ui, repo, modheads, opts.get(r'update'), None, None)
5449 return postincoming(ui, repo, modheads, opts.get(r'update'), None, None)
5450
5450
5451 @command('^update|up|checkout|co',
5451 @command('^update|up|checkout|co',
5452 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5452 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5453 ('c', 'check', None, _('require clean working directory')),
5453 ('c', 'check', None, _('require clean working directory')),
5454 ('m', 'merge', None, _('merge uncommitted changes')),
5454 ('m', 'merge', None, _('merge uncommitted changes')),
5455 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5455 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5456 ('r', 'rev', '', _('revision'), _('REV'))
5456 ('r', 'rev', '', _('revision'), _('REV'))
5457 ] + mergetoolopts,
5457 ] + mergetoolopts,
5458 _('[-C|-c|-m] [-d DATE] [[-r] REV]'))
5458 _('[-C|-c|-m] [-d DATE] [[-r] REV]'))
5459 def update(ui, repo, node=None, **opts):
5459 def update(ui, repo, node=None, **opts):
5460 """update working directory (or switch revisions)
5460 """update working directory (or switch revisions)
5461
5461
5462 Update the repository's working directory to the specified
5462 Update the repository's working directory to the specified
5463 changeset. If no changeset is specified, update to the tip of the
5463 changeset. If no changeset is specified, update to the tip of the
5464 current named branch and move the active bookmark (see :hg:`help
5464 current named branch and move the active bookmark (see :hg:`help
5465 bookmarks`).
5465 bookmarks`).
5466
5466
5467 Update sets the working directory's parent revision to the specified
5467 Update sets the working directory's parent revision to the specified
5468 changeset (see :hg:`help parents`).
5468 changeset (see :hg:`help parents`).
5469
5469
5470 If the changeset is not a descendant or ancestor of the working
5470 If the changeset is not a descendant or ancestor of the working
5471 directory's parent and there are uncommitted changes, the update is
5471 directory's parent and there are uncommitted changes, the update is
5472 aborted. With the -c/--check option, the working directory is checked
5472 aborted. With the -c/--check option, the working directory is checked
5473 for uncommitted changes; if none are found, the working directory is
5473 for uncommitted changes; if none are found, the working directory is
5474 updated to the specified changeset.
5474 updated to the specified changeset.
5475
5475
5476 .. container:: verbose
5476 .. container:: verbose
5477
5477
5478 The -C/--clean, -c/--check, and -m/--merge options control what
5478 The -C/--clean, -c/--check, and -m/--merge options control what
5479 happens if the working directory contains uncommitted changes.
5479 happens if the working directory contains uncommitted changes.
5480 At most of one of them can be specified.
5480 At most of one of them can be specified.
5481
5481
5482 1. If no option is specified, and if
5482 1. If no option is specified, and if
5483 the requested changeset is an ancestor or descendant of
5483 the requested changeset is an ancestor or descendant of
5484 the working directory's parent, the uncommitted changes
5484 the working directory's parent, the uncommitted changes
5485 are merged into the requested changeset and the merged
5485 are merged into the requested changeset and the merged
5486 result is left uncommitted. If the requested changeset is
5486 result is left uncommitted. If the requested changeset is
5487 not an ancestor or descendant (that is, it is on another
5487 not an ancestor or descendant (that is, it is on another
5488 branch), the update is aborted and the uncommitted changes
5488 branch), the update is aborted and the uncommitted changes
5489 are preserved.
5489 are preserved.
5490
5490
5491 2. With the -m/--merge option, the update is allowed even if the
5491 2. With the -m/--merge option, the update is allowed even if the
5492 requested changeset is not an ancestor or descendant of
5492 requested changeset is not an ancestor or descendant of
5493 the working directory's parent.
5493 the working directory's parent.
5494
5494
5495 3. With the -c/--check option, the update is aborted and the
5495 3. With the -c/--check option, the update is aborted and the
5496 uncommitted changes are preserved.
5496 uncommitted changes are preserved.
5497
5497
5498 4. With the -C/--clean option, uncommitted changes are discarded and
5498 4. With the -C/--clean option, uncommitted changes are discarded and
5499 the working directory is updated to the requested changeset.
5499 the working directory is updated to the requested changeset.
5500
5500
5501 To cancel an uncommitted merge (and lose your changes), use
5501 To cancel an uncommitted merge (and lose your changes), use
5502 :hg:`merge --abort`.
5502 :hg:`merge --abort`.
5503
5503
5504 Use null as the changeset to remove the working directory (like
5504 Use null as the changeset to remove the working directory (like
5505 :hg:`clone -U`).
5505 :hg:`clone -U`).
5506
5506
5507 If you want to revert just one file to an older revision, use
5507 If you want to revert just one file to an older revision, use
5508 :hg:`revert [-r REV] NAME`.
5508 :hg:`revert [-r REV] NAME`.
5509
5509
5510 See :hg:`help dates` for a list of formats valid for -d/--date.
5510 See :hg:`help dates` for a list of formats valid for -d/--date.
5511
5511
5512 Returns 0 on success, 1 if there are unresolved files.
5512 Returns 0 on success, 1 if there are unresolved files.
5513 """
5513 """
5514 rev = opts.get(r'rev')
5514 rev = opts.get(r'rev')
5515 date = opts.get(r'date')
5515 date = opts.get(r'date')
5516 clean = opts.get(r'clean')
5516 clean = opts.get(r'clean')
5517 check = opts.get(r'check')
5517 check = opts.get(r'check')
5518 merge = opts.get(r'merge')
5518 merge = opts.get(r'merge')
5519 if rev and node:
5519 if rev and node:
5520 raise error.Abort(_("please specify just one revision"))
5520 raise error.Abort(_("please specify just one revision"))
5521
5521
5522 if ui.configbool('commands', 'update.requiredest'):
5522 if ui.configbool('commands', 'update.requiredest'):
5523 if not node and not rev and not date:
5523 if not node and not rev and not date:
5524 raise error.Abort(_('you must specify a destination'),
5524 raise error.Abort(_('you must specify a destination'),
5525 hint=_('for example: hg update ".::"'))
5525 hint=_('for example: hg update ".::"'))
5526
5526
5527 if rev is None or rev == '':
5527 if rev is None or rev == '':
5528 rev = node
5528 rev = node
5529
5529
5530 if date and rev is not None:
5530 if date and rev is not None:
5531 raise error.Abort(_("you can't specify a revision and a date"))
5531 raise error.Abort(_("you can't specify a revision and a date"))
5532
5532
5533 if len([x for x in (clean, check, merge) if x]) > 1:
5533 if len([x for x in (clean, check, merge) if x]) > 1:
5534 raise error.Abort(_("can only specify one of -C/--clean, -c/--check, "
5534 raise error.Abort(_("can only specify one of -C/--clean, -c/--check, "
5535 "or -m/--merge"))
5535 "or -m/--merge"))
5536
5536
5537 updatecheck = None
5537 updatecheck = None
5538 if check:
5538 if check:
5539 updatecheck = 'abort'
5539 updatecheck = 'abort'
5540 elif merge:
5540 elif merge:
5541 updatecheck = 'none'
5541 updatecheck = 'none'
5542
5542
5543 with repo.wlock():
5543 with repo.wlock():
5544 cmdutil.clearunfinished(repo)
5544 cmdutil.clearunfinished(repo)
5545
5545
5546 if date:
5546 if date:
5547 rev = cmdutil.finddate(ui, repo, date)
5547 rev = cmdutil.finddate(ui, repo, date)
5548
5548
5549 # if we defined a bookmark, we have to remember the original name
5549 # if we defined a bookmark, we have to remember the original name
5550 brev = rev
5550 brev = rev
5551 if rev:
5551 if rev:
5552 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
5552 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
5553 ctx = scmutil.revsingle(repo, rev, rev)
5553 ctx = scmutil.revsingle(repo, rev, rev)
5554 rev = ctx.rev()
5554 rev = ctx.rev()
5555 if ctx.hidden():
5555 if ctx.hidden():
5556 ctxstr = ctx.hex()[:12]
5556 ctxstr = ctx.hex()[:12]
5557 ui.warn(_("updating to a hidden changeset %s\n") % ctxstr)
5557 ui.warn(_("updating to a hidden changeset %s\n") % ctxstr)
5558
5558
5559 if ctx.obsolete():
5559 if ctx.obsolete():
5560 obsfatemsg = obsutil._getfilteredreason(repo, ctxstr, ctx)
5560 obsfatemsg = obsutil._getfilteredreason(repo, ctxstr, ctx)
5561 ui.warn("(%s)\n" % obsfatemsg)
5561 ui.warn("(%s)\n" % obsfatemsg)
5562
5562
5563 repo.ui.setconfig('ui', 'forcemerge', opts.get(r'tool'), 'update')
5563 repo.ui.setconfig('ui', 'forcemerge', opts.get(r'tool'), 'update')
5564
5564
5565 return hg.updatetotally(ui, repo, rev, brev, clean=clean,
5565 return hg.updatetotally(ui, repo, rev, brev, clean=clean,
5566 updatecheck=updatecheck)
5566 updatecheck=updatecheck)
5567
5567
5568 @command('verify', [])
5568 @command('verify', [])
5569 def verify(ui, repo):
5569 def verify(ui, repo):
5570 """verify the integrity of the repository
5570 """verify the integrity of the repository
5571
5571
5572 Verify the integrity of the current repository.
5572 Verify the integrity of the current repository.
5573
5573
5574 This will perform an extensive check of the repository's
5574 This will perform an extensive check of the repository's
5575 integrity, validating the hashes and checksums of each entry in
5575 integrity, validating the hashes and checksums of each entry in
5576 the changelog, manifest, and tracked files, as well as the
5576 the changelog, manifest, and tracked files, as well as the
5577 integrity of their crosslinks and indices.
5577 integrity of their crosslinks and indices.
5578
5578
5579 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
5579 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
5580 for more information about recovery from corruption of the
5580 for more information about recovery from corruption of the
5581 repository.
5581 repository.
5582
5582
5583 Returns 0 on success, 1 if errors are encountered.
5583 Returns 0 on success, 1 if errors are encountered.
5584 """
5584 """
5585 return hg.verify(repo)
5585 return hg.verify(repo)
5586
5586
5587 @command('version', [] + formatteropts, norepo=True, cmdtype=readonly)
5587 @command('version', [] + formatteropts, norepo=True, cmdtype=readonly)
5588 def version_(ui, **opts):
5588 def version_(ui, **opts):
5589 """output version and copyright information"""
5589 """output version and copyright information"""
5590 opts = pycompat.byteskwargs(opts)
5590 opts = pycompat.byteskwargs(opts)
5591 if ui.verbose:
5591 if ui.verbose:
5592 ui.pager('version')
5592 ui.pager('version')
5593 fm = ui.formatter("version", opts)
5593 fm = ui.formatter("version", opts)
5594 fm.startitem()
5594 fm.startitem()
5595 fm.write("ver", _("Mercurial Distributed SCM (version %s)\n"),
5595 fm.write("ver", _("Mercurial Distributed SCM (version %s)\n"),
5596 util.version())
5596 util.version())
5597 license = _(
5597 license = _(
5598 "(see https://mercurial-scm.org for more information)\n"
5598 "(see https://mercurial-scm.org for more information)\n"
5599 "\nCopyright (C) 2005-2018 Matt Mackall and others\n"
5599 "\nCopyright (C) 2005-2018 Matt Mackall and others\n"
5600 "This is free software; see the source for copying conditions. "
5600 "This is free software; see the source for copying conditions. "
5601 "There is NO\nwarranty; "
5601 "There is NO\nwarranty; "
5602 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5602 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5603 )
5603 )
5604 if not ui.quiet:
5604 if not ui.quiet:
5605 fm.plain(license)
5605 fm.plain(license)
5606
5606
5607 if ui.verbose:
5607 if ui.verbose:
5608 fm.plain(_("\nEnabled extensions:\n\n"))
5608 fm.plain(_("\nEnabled extensions:\n\n"))
5609 # format names and versions into columns
5609 # format names and versions into columns
5610 names = []
5610 names = []
5611 vers = []
5611 vers = []
5612 isinternals = []
5612 isinternals = []
5613 for name, module in extensions.extensions():
5613 for name, module in extensions.extensions():
5614 names.append(name)
5614 names.append(name)
5615 vers.append(extensions.moduleversion(module) or None)
5615 vers.append(extensions.moduleversion(module) or None)
5616 isinternals.append(extensions.ismoduleinternal(module))
5616 isinternals.append(extensions.ismoduleinternal(module))
5617 fn = fm.nested("extensions")
5617 fn = fm.nested("extensions")
5618 if names:
5618 if names:
5619 namefmt = " %%-%ds " % max(len(n) for n in names)
5619 namefmt = " %%-%ds " % max(len(n) for n in names)
5620 places = [_("external"), _("internal")]
5620 places = [_("external"), _("internal")]
5621 for n, v, p in zip(names, vers, isinternals):
5621 for n, v, p in zip(names, vers, isinternals):
5622 fn.startitem()
5622 fn.startitem()
5623 fn.condwrite(ui.verbose, "name", namefmt, n)
5623 fn.condwrite(ui.verbose, "name", namefmt, n)
5624 if ui.verbose:
5624 if ui.verbose:
5625 fn.plain("%s " % places[p])
5625 fn.plain("%s " % places[p])
5626 fn.data(bundled=p)
5626 fn.data(bundled=p)
5627 fn.condwrite(ui.verbose and v, "ver", "%s", v)
5627 fn.condwrite(ui.verbose and v, "ver", "%s", v)
5628 if ui.verbose:
5628 if ui.verbose:
5629 fn.plain("\n")
5629 fn.plain("\n")
5630 fn.end()
5630 fn.end()
5631 fm.end()
5631 fm.end()
5632
5632
5633 def loadcmdtable(ui, name, cmdtable):
5633 def loadcmdtable(ui, name, cmdtable):
5634 """Load command functions from specified cmdtable
5634 """Load command functions from specified cmdtable
5635 """
5635 """
5636 overrides = [cmd for cmd in cmdtable if cmd in table]
5636 overrides = [cmd for cmd in cmdtable if cmd in table]
5637 if overrides:
5637 if overrides:
5638 ui.warn(_("extension '%s' overrides commands: %s\n")
5638 ui.warn(_("extension '%s' overrides commands: %s\n")
5639 % (name, " ".join(overrides)))
5639 % (name, " ".join(overrides)))
5640 table.update(cmdtable)
5640 table.update(cmdtable)
@@ -1,1142 +1,1143 b''
1 # hg.py - repository classes for mercurial
1 # hg.py - repository classes for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
4 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
5 #
5 #
6 # This software may be used and distributed according to the terms of the
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
7 # GNU General Public License version 2 or any later version.
8
8
9 from __future__ import absolute_import
9 from __future__ import absolute_import
10
10
11 import errno
11 import errno
12 import hashlib
12 import hashlib
13 import os
13 import os
14 import shutil
14 import shutil
15 import stat
15 import stat
16
16
17 from .i18n import _
17 from .i18n import _
18 from .node import (
18 from .node import (
19 nullid,
19 nullid,
20 )
20 )
21
21
22 from . import (
22 from . import (
23 bookmarks,
23 bookmarks,
24 bundlerepo,
24 bundlerepo,
25 cacheutil,
25 cacheutil,
26 cmdutil,
26 cmdutil,
27 destutil,
27 destutil,
28 discovery,
28 discovery,
29 error,
29 error,
30 exchange,
30 exchange,
31 extensions,
31 extensions,
32 httppeer,
32 httppeer,
33 localrepo,
33 localrepo,
34 lock,
34 lock,
35 logcmdutil,
35 logcmdutil,
36 logexchange,
36 logexchange,
37 merge as mergemod,
37 merge as mergemod,
38 node,
38 node,
39 phases,
39 phases,
40 scmutil,
40 scmutil,
41 sshpeer,
41 sshpeer,
42 statichttprepo,
42 statichttprepo,
43 ui as uimod,
43 ui as uimod,
44 unionrepo,
44 unionrepo,
45 url,
45 url,
46 util,
46 util,
47 verify as verifymod,
47 verify as verifymod,
48 vfs as vfsmod,
48 vfs as vfsmod,
49 )
49 )
50
50
51 from .utils import (
51 from .utils import (
52 stringutil,
52 stringutil,
53 )
53 )
54
54
55 release = lock.release
55 release = lock.release
56
56
57 # shared features
57 # shared features
58 sharedbookmarks = 'bookmarks'
58 sharedbookmarks = 'bookmarks'
59
59
60 def _local(path):
60 def _local(path):
61 path = util.expandpath(util.urllocalpath(path))
61 path = util.expandpath(util.urllocalpath(path))
62 return (os.path.isfile(path) and bundlerepo or localrepo)
62 return (os.path.isfile(path) and bundlerepo or localrepo)
63
63
64 def addbranchrevs(lrepo, other, branches, revs):
64 def addbranchrevs(lrepo, other, branches, revs):
65 peer = other.peer() # a courtesy to callers using a localrepo for other
65 peer = other.peer() # a courtesy to callers using a localrepo for other
66 hashbranch, branches = branches
66 hashbranch, branches = branches
67 if not hashbranch and not branches:
67 if not hashbranch and not branches:
68 x = revs or None
68 x = revs or None
69 if util.safehasattr(revs, 'first'):
69 if util.safehasattr(revs, 'first'):
70 y = revs.first()
70 y = revs.first()
71 elif revs:
71 elif revs:
72 y = revs[0]
72 y = revs[0]
73 else:
73 else:
74 y = None
74 y = None
75 return x, y
75 return x, y
76 if revs:
76 if revs:
77 revs = list(revs)
77 revs = list(revs)
78 else:
78 else:
79 revs = []
79 revs = []
80
80
81 if not peer.capable('branchmap'):
81 if not peer.capable('branchmap'):
82 if branches:
82 if branches:
83 raise error.Abort(_("remote branch lookup not supported"))
83 raise error.Abort(_("remote branch lookup not supported"))
84 revs.append(hashbranch)
84 revs.append(hashbranch)
85 return revs, revs[0]
85 return revs, revs[0]
86 branchmap = peer.branchmap()
86 branchmap = peer.branchmap()
87
87
88 def primary(branch):
88 def primary(branch):
89 if branch == '.':
89 if branch == '.':
90 if not lrepo:
90 if not lrepo:
91 raise error.Abort(_("dirstate branch not accessible"))
91 raise error.Abort(_("dirstate branch not accessible"))
92 branch = lrepo.dirstate.branch()
92 branch = lrepo.dirstate.branch()
93 if branch in branchmap:
93 if branch in branchmap:
94 revs.extend(node.hex(r) for r in reversed(branchmap[branch]))
94 revs.extend(node.hex(r) for r in reversed(branchmap[branch]))
95 return True
95 return True
96 else:
96 else:
97 return False
97 return False
98
98
99 for branch in branches:
99 for branch in branches:
100 if not primary(branch):
100 if not primary(branch):
101 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
101 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
102 if hashbranch:
102 if hashbranch:
103 if not primary(hashbranch):
103 if not primary(hashbranch):
104 revs.append(hashbranch)
104 revs.append(hashbranch)
105 return revs, revs[0]
105 return revs, revs[0]
106
106
107 def parseurl(path, branches=None):
107 def parseurl(path, branches=None):
108 '''parse url#branch, returning (url, (branch, branches))'''
108 '''parse url#branch, returning (url, (branch, branches))'''
109
109
110 u = util.url(path)
110 u = util.url(path)
111 branch = None
111 branch = None
112 if u.fragment:
112 if u.fragment:
113 branch = u.fragment
113 branch = u.fragment
114 u.fragment = None
114 u.fragment = None
115 return bytes(u), (branch, branches or [])
115 return bytes(u), (branch, branches or [])
116
116
117 schemes = {
117 schemes = {
118 'bundle': bundlerepo,
118 'bundle': bundlerepo,
119 'union': unionrepo,
119 'union': unionrepo,
120 'file': _local,
120 'file': _local,
121 'http': httppeer,
121 'http': httppeer,
122 'https': httppeer,
122 'https': httppeer,
123 'ssh': sshpeer,
123 'ssh': sshpeer,
124 'static-http': statichttprepo,
124 'static-http': statichttprepo,
125 }
125 }
126
126
127 def _peerlookup(path):
127 def _peerlookup(path):
128 u = util.url(path)
128 u = util.url(path)
129 scheme = u.scheme or 'file'
129 scheme = u.scheme or 'file'
130 thing = schemes.get(scheme) or schemes['file']
130 thing = schemes.get(scheme) or schemes['file']
131 try:
131 try:
132 return thing(path)
132 return thing(path)
133 except TypeError:
133 except TypeError:
134 # we can't test callable(thing) because 'thing' can be an unloaded
134 # we can't test callable(thing) because 'thing' can be an unloaded
135 # module that implements __call__
135 # module that implements __call__
136 if not util.safehasattr(thing, 'instance'):
136 if not util.safehasattr(thing, 'instance'):
137 raise
137 raise
138 return thing
138 return thing
139
139
140 def islocal(repo):
140 def islocal(repo):
141 '''return true if repo (or path pointing to repo) is local'''
141 '''return true if repo (or path pointing to repo) is local'''
142 if isinstance(repo, bytes):
142 if isinstance(repo, bytes):
143 try:
143 try:
144 return _peerlookup(repo).islocal(repo)
144 return _peerlookup(repo).islocal(repo)
145 except AttributeError:
145 except AttributeError:
146 return False
146 return False
147 return repo.local()
147 return repo.local()
148
148
149 def openpath(ui, path):
149 def openpath(ui, path):
150 '''open path with open if local, url.open if remote'''
150 '''open path with open if local, url.open if remote'''
151 pathurl = util.url(path, parsequery=False, parsefragment=False)
151 pathurl = util.url(path, parsequery=False, parsefragment=False)
152 if pathurl.islocal():
152 if pathurl.islocal():
153 return util.posixfile(pathurl.localpath(), 'rb')
153 return util.posixfile(pathurl.localpath(), 'rb')
154 else:
154 else:
155 return url.open(ui, path)
155 return url.open(ui, path)
156
156
157 # a list of (ui, repo) functions called for wire peer initialization
157 # a list of (ui, repo) functions called for wire peer initialization
158 wirepeersetupfuncs = []
158 wirepeersetupfuncs = []
159
159
160 def _peerorrepo(ui, path, create=False, presetupfuncs=None):
160 def _peerorrepo(ui, path, create=False, presetupfuncs=None):
161 """return a repository object for the specified path"""
161 """return a repository object for the specified path"""
162 obj = _peerlookup(path).instance(ui, path, create)
162 obj = _peerlookup(path).instance(ui, path, create)
163 ui = getattr(obj, "ui", ui)
163 ui = getattr(obj, "ui", ui)
164 for f in presetupfuncs or []:
164 for f in presetupfuncs or []:
165 f(ui, obj)
165 f(ui, obj)
166 for name, module in extensions.extensions(ui):
166 for name, module in extensions.extensions(ui):
167 hook = getattr(module, 'reposetup', None)
167 hook = getattr(module, 'reposetup', None)
168 if hook:
168 if hook:
169 hook(ui, obj)
169 hook(ui, obj)
170 if not obj.local():
170 if not obj.local():
171 for f in wirepeersetupfuncs:
171 for f in wirepeersetupfuncs:
172 f(ui, obj)
172 f(ui, obj)
173 return obj
173 return obj
174
174
175 def repository(ui, path='', create=False, presetupfuncs=None):
175 def repository(ui, path='', create=False, presetupfuncs=None):
176 """return a repository object for the specified path"""
176 """return a repository object for the specified path"""
177 peer = _peerorrepo(ui, path, create, presetupfuncs=presetupfuncs)
177 peer = _peerorrepo(ui, path, create, presetupfuncs=presetupfuncs)
178 repo = peer.local()
178 repo = peer.local()
179 if not repo:
179 if not repo:
180 raise error.Abort(_("repository '%s' is not local") %
180 raise error.Abort(_("repository '%s' is not local") %
181 (path or peer.url()))
181 (path or peer.url()))
182 return repo.filtered('visible')
182 return repo.filtered('visible')
183
183
184 def peer(uiorrepo, opts, path, create=False):
184 def peer(uiorrepo, opts, path, create=False):
185 '''return a repository peer for the specified path'''
185 '''return a repository peer for the specified path'''
186 rui = remoteui(uiorrepo, opts)
186 rui = remoteui(uiorrepo, opts)
187 return _peerorrepo(rui, path, create).peer()
187 return _peerorrepo(rui, path, create).peer()
188
188
189 def defaultdest(source):
189 def defaultdest(source):
190 '''return default destination of clone if none is given
190 '''return default destination of clone if none is given
191
191
192 >>> defaultdest(b'foo')
192 >>> defaultdest(b'foo')
193 'foo'
193 'foo'
194 >>> defaultdest(b'/foo/bar')
194 >>> defaultdest(b'/foo/bar')
195 'bar'
195 'bar'
196 >>> defaultdest(b'/')
196 >>> defaultdest(b'/')
197 ''
197 ''
198 >>> defaultdest(b'')
198 >>> defaultdest(b'')
199 ''
199 ''
200 >>> defaultdest(b'http://example.org/')
200 >>> defaultdest(b'http://example.org/')
201 ''
201 ''
202 >>> defaultdest(b'http://example.org/foo/')
202 >>> defaultdest(b'http://example.org/foo/')
203 'foo'
203 'foo'
204 '''
204 '''
205 path = util.url(source).path
205 path = util.url(source).path
206 if not path:
206 if not path:
207 return ''
207 return ''
208 return os.path.basename(os.path.normpath(path))
208 return os.path.basename(os.path.normpath(path))
209
209
210 def sharedreposource(repo):
210 def sharedreposource(repo):
211 """Returns repository object for source repository of a shared repo.
211 """Returns repository object for source repository of a shared repo.
212
212
213 If repo is not a shared repository, returns None.
213 If repo is not a shared repository, returns None.
214 """
214 """
215 if repo.sharedpath == repo.path:
215 if repo.sharedpath == repo.path:
216 return None
216 return None
217
217
218 if util.safehasattr(repo, 'srcrepo') and repo.srcrepo:
218 if util.safehasattr(repo, 'srcrepo') and repo.srcrepo:
219 return repo.srcrepo
219 return repo.srcrepo
220
220
221 # the sharedpath always ends in the .hg; we want the path to the repo
221 # the sharedpath always ends in the .hg; we want the path to the repo
222 source = repo.vfs.split(repo.sharedpath)[0]
222 source = repo.vfs.split(repo.sharedpath)[0]
223 srcurl, branches = parseurl(source)
223 srcurl, branches = parseurl(source)
224 srcrepo = repository(repo.ui, srcurl)
224 srcrepo = repository(repo.ui, srcurl)
225 repo.srcrepo = srcrepo
225 repo.srcrepo = srcrepo
226 return srcrepo
226 return srcrepo
227
227
228 def share(ui, source, dest=None, update=True, bookmarks=True, defaultpath=None,
228 def share(ui, source, dest=None, update=True, bookmarks=True, defaultpath=None,
229 relative=False):
229 relative=False):
230 '''create a shared repository'''
230 '''create a shared repository'''
231
231
232 if not islocal(source):
232 if not islocal(source):
233 raise error.Abort(_('can only share local repositories'))
233 raise error.Abort(_('can only share local repositories'))
234
234
235 if not dest:
235 if not dest:
236 dest = defaultdest(source)
236 dest = defaultdest(source)
237 else:
237 else:
238 dest = ui.expandpath(dest)
238 dest = ui.expandpath(dest)
239
239
240 if isinstance(source, bytes):
240 if isinstance(source, bytes):
241 origsource = ui.expandpath(source)
241 origsource = ui.expandpath(source)
242 source, branches = parseurl(origsource)
242 source, branches = parseurl(origsource)
243 srcrepo = repository(ui, source)
243 srcrepo = repository(ui, source)
244 rev, checkout = addbranchrevs(srcrepo, srcrepo, branches, None)
244 rev, checkout = addbranchrevs(srcrepo, srcrepo, branches, None)
245 else:
245 else:
246 srcrepo = source.local()
246 srcrepo = source.local()
247 origsource = source = srcrepo.url()
247 origsource = source = srcrepo.url()
248 checkout = None
248 checkout = None
249
249
250 sharedpath = srcrepo.sharedpath # if our source is already sharing
250 sharedpath = srcrepo.sharedpath # if our source is already sharing
251
251
252 destwvfs = vfsmod.vfs(dest, realpath=True)
252 destwvfs = vfsmod.vfs(dest, realpath=True)
253 destvfs = vfsmod.vfs(os.path.join(destwvfs.base, '.hg'), realpath=True)
253 destvfs = vfsmod.vfs(os.path.join(destwvfs.base, '.hg'), realpath=True)
254
254
255 if destvfs.lexists():
255 if destvfs.lexists():
256 raise error.Abort(_('destination already exists'))
256 raise error.Abort(_('destination already exists'))
257
257
258 if not destwvfs.isdir():
258 if not destwvfs.isdir():
259 destwvfs.mkdir()
259 destwvfs.mkdir()
260 destvfs.makedir()
260 destvfs.makedir()
261
261
262 requirements = ''
262 requirements = ''
263 try:
263 try:
264 requirements = srcrepo.vfs.read('requires')
264 requirements = srcrepo.vfs.read('requires')
265 except IOError as inst:
265 except IOError as inst:
266 if inst.errno != errno.ENOENT:
266 if inst.errno != errno.ENOENT:
267 raise
267 raise
268
268
269 if relative:
269 if relative:
270 try:
270 try:
271 sharedpath = os.path.relpath(sharedpath, destvfs.base)
271 sharedpath = os.path.relpath(sharedpath, destvfs.base)
272 requirements += 'relshared\n'
272 requirements += 'relshared\n'
273 except (IOError, ValueError) as e:
273 except (IOError, ValueError) as e:
274 # ValueError is raised on Windows if the drive letters differ on
274 # ValueError is raised on Windows if the drive letters differ on
275 # each path
275 # each path
276 raise error.Abort(_('cannot calculate relative path'),
276 raise error.Abort(_('cannot calculate relative path'),
277 hint=stringutil.forcebytestr(e))
277 hint=stringutil.forcebytestr(e))
278 else:
278 else:
279 requirements += 'shared\n'
279 requirements += 'shared\n'
280
280
281 destvfs.write('requires', requirements)
281 destvfs.write('requires', requirements)
282 destvfs.write('sharedpath', sharedpath)
282 destvfs.write('sharedpath', sharedpath)
283
283
284 r = repository(ui, destwvfs.base)
284 r = repository(ui, destwvfs.base)
285 postshare(srcrepo, r, bookmarks=bookmarks, defaultpath=defaultpath)
285 postshare(srcrepo, r, bookmarks=bookmarks, defaultpath=defaultpath)
286 _postshareupdate(r, update, checkout=checkout)
286 _postshareupdate(r, update, checkout=checkout)
287 return r
287 return r
288
288
289 def unshare(ui, repo):
289 def unshare(ui, repo):
290 """convert a shared repository to a normal one
290 """convert a shared repository to a normal one
291
291
292 Copy the store data to the repo and remove the sharedpath data.
292 Copy the store data to the repo and remove the sharedpath data.
293 """
293 """
294
294
295 destlock = lock = None
295 destlock = lock = None
296 lock = repo.lock()
296 lock = repo.lock()
297 try:
297 try:
298 # we use locks here because if we race with commit, we
298 # we use locks here because if we race with commit, we
299 # can end up with extra data in the cloned revlogs that's
299 # can end up with extra data in the cloned revlogs that's
300 # not pointed to by changesets, thus causing verify to
300 # not pointed to by changesets, thus causing verify to
301 # fail
301 # fail
302
302
303 destlock = copystore(ui, repo, repo.path)
303 destlock = copystore(ui, repo, repo.path)
304
304
305 sharefile = repo.vfs.join('sharedpath')
305 sharefile = repo.vfs.join('sharedpath')
306 util.rename(sharefile, sharefile + '.old')
306 util.rename(sharefile, sharefile + '.old')
307
307
308 repo.requirements.discard('shared')
308 repo.requirements.discard('shared')
309 repo.requirements.discard('relshared')
309 repo.requirements.discard('relshared')
310 repo._writerequirements()
310 repo._writerequirements()
311 finally:
311 finally:
312 destlock and destlock.release()
312 destlock and destlock.release()
313 lock and lock.release()
313 lock and lock.release()
314
314
315 # update store, spath, svfs and sjoin of repo
315 # update store, spath, svfs and sjoin of repo
316 repo.unfiltered().__init__(repo.baseui, repo.root)
316 repo.unfiltered().__init__(repo.baseui, repo.root)
317
317
318 # TODO: figure out how to access subrepos that exist, but were previously
318 # TODO: figure out how to access subrepos that exist, but were previously
319 # removed from .hgsub
319 # removed from .hgsub
320 c = repo['.']
320 c = repo['.']
321 subs = c.substate
321 subs = c.substate
322 for s in sorted(subs):
322 for s in sorted(subs):
323 c.sub(s).unshare()
323 c.sub(s).unshare()
324
324
325 def postshare(sourcerepo, destrepo, bookmarks=True, defaultpath=None):
325 def postshare(sourcerepo, destrepo, bookmarks=True, defaultpath=None):
326 """Called after a new shared repo is created.
326 """Called after a new shared repo is created.
327
327
328 The new repo only has a requirements file and pointer to the source.
328 The new repo only has a requirements file and pointer to the source.
329 This function configures additional shared data.
329 This function configures additional shared data.
330
330
331 Extensions can wrap this function and write additional entries to
331 Extensions can wrap this function and write additional entries to
332 destrepo/.hg/shared to indicate additional pieces of data to be shared.
332 destrepo/.hg/shared to indicate additional pieces of data to be shared.
333 """
333 """
334 default = defaultpath or sourcerepo.ui.config('paths', 'default')
334 default = defaultpath or sourcerepo.ui.config('paths', 'default')
335 if default:
335 if default:
336 template = ('[paths]\n'
336 template = ('[paths]\n'
337 'default = %s\n')
337 'default = %s\n')
338 destrepo.vfs.write('hgrc', util.tonativeeol(template % default))
338 destrepo.vfs.write('hgrc', util.tonativeeol(template % default))
339
339
340 with destrepo.wlock():
340 with destrepo.wlock():
341 if bookmarks:
341 if bookmarks:
342 destrepo.vfs.write('shared', sharedbookmarks + '\n')
342 destrepo.vfs.write('shared', sharedbookmarks + '\n')
343
343
344 def _postshareupdate(repo, update, checkout=None):
344 def _postshareupdate(repo, update, checkout=None):
345 """Maybe perform a working directory update after a shared repo is created.
345 """Maybe perform a working directory update after a shared repo is created.
346
346
347 ``update`` can be a boolean or a revision to update to.
347 ``update`` can be a boolean or a revision to update to.
348 """
348 """
349 if not update:
349 if not update:
350 return
350 return
351
351
352 repo.ui.status(_("updating working directory\n"))
352 repo.ui.status(_("updating working directory\n"))
353 if update is not True:
353 if update is not True:
354 checkout = update
354 checkout = update
355 for test in (checkout, 'default', 'tip'):
355 for test in (checkout, 'default', 'tip'):
356 if test is None:
356 if test is None:
357 continue
357 continue
358 try:
358 try:
359 uprev = repo.lookup(test)
359 uprev = repo.lookup(test)
360 break
360 break
361 except error.RepoLookupError:
361 except error.RepoLookupError:
362 continue
362 continue
363 _update(repo, uprev)
363 _update(repo, uprev)
364
364
365 def copystore(ui, srcrepo, destpath):
365 def copystore(ui, srcrepo, destpath):
366 '''copy files from store of srcrepo in destpath
366 '''copy files from store of srcrepo in destpath
367
367
368 returns destlock
368 returns destlock
369 '''
369 '''
370 destlock = None
370 destlock = None
371 try:
371 try:
372 hardlink = None
372 hardlink = None
373 num = 0
373 num = 0
374 closetopic = [None]
374 closetopic = [None]
375 def prog(topic, pos):
375 def prog(topic, pos):
376 if pos is None:
376 if pos is None:
377 closetopic[0] = topic
377 closetopic[0] = topic
378 else:
378 else:
379 ui.progress(topic, pos + num)
379 ui.progress(topic, pos + num)
380 srcpublishing = srcrepo.publishing()
380 srcpublishing = srcrepo.publishing()
381 srcvfs = vfsmod.vfs(srcrepo.sharedpath)
381 srcvfs = vfsmod.vfs(srcrepo.sharedpath)
382 dstvfs = vfsmod.vfs(destpath)
382 dstvfs = vfsmod.vfs(destpath)
383 for f in srcrepo.store.copylist():
383 for f in srcrepo.store.copylist():
384 if srcpublishing and f.endswith('phaseroots'):
384 if srcpublishing and f.endswith('phaseroots'):
385 continue
385 continue
386 dstbase = os.path.dirname(f)
386 dstbase = os.path.dirname(f)
387 if dstbase and not dstvfs.exists(dstbase):
387 if dstbase and not dstvfs.exists(dstbase):
388 dstvfs.mkdir(dstbase)
388 dstvfs.mkdir(dstbase)
389 if srcvfs.exists(f):
389 if srcvfs.exists(f):
390 if f.endswith('data'):
390 if f.endswith('data'):
391 # 'dstbase' may be empty (e.g. revlog format 0)
391 # 'dstbase' may be empty (e.g. revlog format 0)
392 lockfile = os.path.join(dstbase, "lock")
392 lockfile = os.path.join(dstbase, "lock")
393 # lock to avoid premature writing to the target
393 # lock to avoid premature writing to the target
394 destlock = lock.lock(dstvfs, lockfile)
394 destlock = lock.lock(dstvfs, lockfile)
395 hardlink, n = util.copyfiles(srcvfs.join(f), dstvfs.join(f),
395 hardlink, n = util.copyfiles(srcvfs.join(f), dstvfs.join(f),
396 hardlink, progress=prog)
396 hardlink, progress=prog)
397 num += n
397 num += n
398 if hardlink:
398 if hardlink:
399 ui.debug("linked %d files\n" % num)
399 ui.debug("linked %d files\n" % num)
400 if closetopic[0]:
400 if closetopic[0]:
401 ui.progress(closetopic[0], None)
401 ui.progress(closetopic[0], None)
402 else:
402 else:
403 ui.debug("copied %d files\n" % num)
403 ui.debug("copied %d files\n" % num)
404 if closetopic[0]:
404 if closetopic[0]:
405 ui.progress(closetopic[0], None)
405 ui.progress(closetopic[0], None)
406 return destlock
406 return destlock
407 except: # re-raises
407 except: # re-raises
408 release(destlock)
408 release(destlock)
409 raise
409 raise
410
410
411 def clonewithshare(ui, peeropts, sharepath, source, srcpeer, dest, pull=False,
411 def clonewithshare(ui, peeropts, sharepath, source, srcpeer, dest, pull=False,
412 rev=None, update=True, stream=False):
412 rev=None, update=True, stream=False):
413 """Perform a clone using a shared repo.
413 """Perform a clone using a shared repo.
414
414
415 The store for the repository will be located at <sharepath>/.hg. The
415 The store for the repository will be located at <sharepath>/.hg. The
416 specified revisions will be cloned or pulled from "source". A shared repo
416 specified revisions will be cloned or pulled from "source". A shared repo
417 will be created at "dest" and a working copy will be created if "update" is
417 will be created at "dest" and a working copy will be created if "update" is
418 True.
418 True.
419 """
419 """
420 revs = None
420 revs = None
421 if rev:
421 if rev:
422 if not srcpeer.capable('lookup'):
422 if not srcpeer.capable('lookup'):
423 raise error.Abort(_("src repository does not support "
423 raise error.Abort(_("src repository does not support "
424 "revision lookup and so doesn't "
424 "revision lookup and so doesn't "
425 "support clone by revision"))
425 "support clone by revision"))
426 revs = [srcpeer.lookup(r) for r in rev]
426 revs = [srcpeer.lookup(r) for r in rev]
427
427
428 # Obtain a lock before checking for or cloning the pooled repo otherwise
428 # Obtain a lock before checking for or cloning the pooled repo otherwise
429 # 2 clients may race creating or populating it.
429 # 2 clients may race creating or populating it.
430 pooldir = os.path.dirname(sharepath)
430 pooldir = os.path.dirname(sharepath)
431 # lock class requires the directory to exist.
431 # lock class requires the directory to exist.
432 try:
432 try:
433 util.makedir(pooldir, False)
433 util.makedir(pooldir, False)
434 except OSError as e:
434 except OSError as e:
435 if e.errno != errno.EEXIST:
435 if e.errno != errno.EEXIST:
436 raise
436 raise
437
437
438 poolvfs = vfsmod.vfs(pooldir)
438 poolvfs = vfsmod.vfs(pooldir)
439 basename = os.path.basename(sharepath)
439 basename = os.path.basename(sharepath)
440
440
441 with lock.lock(poolvfs, '%s.lock' % basename):
441 with lock.lock(poolvfs, '%s.lock' % basename):
442 if os.path.exists(sharepath):
442 if os.path.exists(sharepath):
443 ui.status(_('(sharing from existing pooled repository %s)\n') %
443 ui.status(_('(sharing from existing pooled repository %s)\n') %
444 basename)
444 basename)
445 else:
445 else:
446 ui.status(_('(sharing from new pooled repository %s)\n') % basename)
446 ui.status(_('(sharing from new pooled repository %s)\n') % basename)
447 # Always use pull mode because hardlinks in share mode don't work
447 # Always use pull mode because hardlinks in share mode don't work
448 # well. Never update because working copies aren't necessary in
448 # well. Never update because working copies aren't necessary in
449 # share mode.
449 # share mode.
450 clone(ui, peeropts, source, dest=sharepath, pull=True,
450 clone(ui, peeropts, source, dest=sharepath, pull=True,
451 rev=rev, update=False, stream=stream)
451 revs=rev, update=False, stream=stream)
452
452
453 # Resolve the value to put in [paths] section for the source.
453 # Resolve the value to put in [paths] section for the source.
454 if islocal(source):
454 if islocal(source):
455 defaultpath = os.path.abspath(util.urllocalpath(source))
455 defaultpath = os.path.abspath(util.urllocalpath(source))
456 else:
456 else:
457 defaultpath = source
457 defaultpath = source
458
458
459 sharerepo = repository(ui, path=sharepath)
459 sharerepo = repository(ui, path=sharepath)
460 share(ui, sharerepo, dest=dest, update=False, bookmarks=False,
460 share(ui, sharerepo, dest=dest, update=False, bookmarks=False,
461 defaultpath=defaultpath)
461 defaultpath=defaultpath)
462
462
463 # We need to perform a pull against the dest repo to fetch bookmarks
463 # We need to perform a pull against the dest repo to fetch bookmarks
464 # and other non-store data that isn't shared by default. In the case of
464 # and other non-store data that isn't shared by default. In the case of
465 # non-existing shared repo, this means we pull from the remote twice. This
465 # non-existing shared repo, this means we pull from the remote twice. This
466 # is a bit weird. But at the time it was implemented, there wasn't an easy
466 # is a bit weird. But at the time it was implemented, there wasn't an easy
467 # way to pull just non-changegroup data.
467 # way to pull just non-changegroup data.
468 destrepo = repository(ui, path=dest)
468 destrepo = repository(ui, path=dest)
469 exchange.pull(destrepo, srcpeer, heads=revs)
469 exchange.pull(destrepo, srcpeer, heads=revs)
470
470
471 _postshareupdate(destrepo, update)
471 _postshareupdate(destrepo, update)
472
472
473 return srcpeer, peer(ui, peeropts, dest)
473 return srcpeer, peer(ui, peeropts, dest)
474
474
475 # Recomputing branch cache might be slow on big repos,
475 # Recomputing branch cache might be slow on big repos,
476 # so just copy it
476 # so just copy it
477 def _copycache(srcrepo, dstcachedir, fname):
477 def _copycache(srcrepo, dstcachedir, fname):
478 """copy a cache from srcrepo to destcachedir (if it exists)"""
478 """copy a cache from srcrepo to destcachedir (if it exists)"""
479 srcbranchcache = srcrepo.vfs.join('cache/%s' % fname)
479 srcbranchcache = srcrepo.vfs.join('cache/%s' % fname)
480 dstbranchcache = os.path.join(dstcachedir, fname)
480 dstbranchcache = os.path.join(dstcachedir, fname)
481 if os.path.exists(srcbranchcache):
481 if os.path.exists(srcbranchcache):
482 if not os.path.exists(dstcachedir):
482 if not os.path.exists(dstcachedir):
483 os.mkdir(dstcachedir)
483 os.mkdir(dstcachedir)
484 util.copyfile(srcbranchcache, dstbranchcache)
484 util.copyfile(srcbranchcache, dstbranchcache)
485
485
486 def clone(ui, peeropts, source, dest=None, pull=False, rev=None,
486 def clone(ui, peeropts, source, dest=None, pull=False, revs=None,
487 update=True, stream=False, branch=None, shareopts=None):
487 update=True, stream=False, branch=None, shareopts=None):
488 """Make a copy of an existing repository.
488 """Make a copy of an existing repository.
489
489
490 Create a copy of an existing repository in a new directory. The
490 Create a copy of an existing repository in a new directory. The
491 source and destination are URLs, as passed to the repository
491 source and destination are URLs, as passed to the repository
492 function. Returns a pair of repository peers, the source and
492 function. Returns a pair of repository peers, the source and
493 newly created destination.
493 newly created destination.
494
494
495 The location of the source is added to the new repository's
495 The location of the source is added to the new repository's
496 .hg/hgrc file, as the default to be used for future pulls and
496 .hg/hgrc file, as the default to be used for future pulls and
497 pushes.
497 pushes.
498
498
499 If an exception is raised, the partly cloned/updated destination
499 If an exception is raised, the partly cloned/updated destination
500 repository will be deleted.
500 repository will be deleted.
501
501
502 Arguments:
502 Arguments:
503
503
504 source: repository object or URL
504 source: repository object or URL
505
505
506 dest: URL of destination repository to create (defaults to base
506 dest: URL of destination repository to create (defaults to base
507 name of source repository)
507 name of source repository)
508
508
509 pull: always pull from source repository, even in local case or if the
509 pull: always pull from source repository, even in local case or if the
510 server prefers streaming
510 server prefers streaming
511
511
512 stream: stream raw data uncompressed from repository (fast over
512 stream: stream raw data uncompressed from repository (fast over
513 LAN, slow over WAN)
513 LAN, slow over WAN)
514
514
515 rev: revision to clone up to (implies pull=True)
515 revs: revision to clone up to (implies pull=True)
516
516
517 update: update working directory after clone completes, if
517 update: update working directory after clone completes, if
518 destination is local repository (True means update to default rev,
518 destination is local repository (True means update to default rev,
519 anything else is treated as a revision)
519 anything else is treated as a revision)
520
520
521 branch: branches to clone
521 branch: branches to clone
522
522
523 shareopts: dict of options to control auto sharing behavior. The "pool" key
523 shareopts: dict of options to control auto sharing behavior. The "pool" key
524 activates auto sharing mode and defines the directory for stores. The
524 activates auto sharing mode and defines the directory for stores. The
525 "mode" key determines how to construct the directory name of the shared
525 "mode" key determines how to construct the directory name of the shared
526 repository. "identity" means the name is derived from the node of the first
526 repository. "identity" means the name is derived from the node of the first
527 changeset in the repository. "remote" means the name is derived from the
527 changeset in the repository. "remote" means the name is derived from the
528 remote's path/URL. Defaults to "identity."
528 remote's path/URL. Defaults to "identity."
529 """
529 """
530
530
531 if isinstance(source, bytes):
531 if isinstance(source, bytes):
532 origsource = ui.expandpath(source)
532 origsource = ui.expandpath(source)
533 source, branches = parseurl(origsource, branch)
533 source, branches = parseurl(origsource, branch)
534 srcpeer = peer(ui, peeropts, source)
534 srcpeer = peer(ui, peeropts, source)
535 else:
535 else:
536 srcpeer = source.peer() # in case we were called with a localrepo
536 srcpeer = source.peer() # in case we were called with a localrepo
537 branches = (None, branch or [])
537 branches = (None, branch or [])
538 origsource = source = srcpeer.url()
538 origsource = source = srcpeer.url()
539 rev, checkout = addbranchrevs(srcpeer, srcpeer, branches, rev)
539 revs, checkout = addbranchrevs(srcpeer, srcpeer, branches, revs)
540
540
541 if dest is None:
541 if dest is None:
542 dest = defaultdest(source)
542 dest = defaultdest(source)
543 if dest:
543 if dest:
544 ui.status(_("destination directory: %s\n") % dest)
544 ui.status(_("destination directory: %s\n") % dest)
545 else:
545 else:
546 dest = ui.expandpath(dest)
546 dest = ui.expandpath(dest)
547
547
548 dest = util.urllocalpath(dest)
548 dest = util.urllocalpath(dest)
549 source = util.urllocalpath(source)
549 source = util.urllocalpath(source)
550
550
551 if not dest:
551 if not dest:
552 raise error.Abort(_("empty destination path is not valid"))
552 raise error.Abort(_("empty destination path is not valid"))
553
553
554 destvfs = vfsmod.vfs(dest, expandpath=True)
554 destvfs = vfsmod.vfs(dest, expandpath=True)
555 if destvfs.lexists():
555 if destvfs.lexists():
556 if not destvfs.isdir():
556 if not destvfs.isdir():
557 raise error.Abort(_("destination '%s' already exists") % dest)
557 raise error.Abort(_("destination '%s' already exists") % dest)
558 elif destvfs.listdir():
558 elif destvfs.listdir():
559 raise error.Abort(_("destination '%s' is not empty") % dest)
559 raise error.Abort(_("destination '%s' is not empty") % dest)
560
560
561 shareopts = shareopts or {}
561 shareopts = shareopts or {}
562 sharepool = shareopts.get('pool')
562 sharepool = shareopts.get('pool')
563 sharenamemode = shareopts.get('mode')
563 sharenamemode = shareopts.get('mode')
564 if sharepool and islocal(dest):
564 if sharepool and islocal(dest):
565 sharepath = None
565 sharepath = None
566 if sharenamemode == 'identity':
566 if sharenamemode == 'identity':
567 # Resolve the name from the initial changeset in the remote
567 # Resolve the name from the initial changeset in the remote
568 # repository. This returns nullid when the remote is empty. It
568 # repository. This returns nullid when the remote is empty. It
569 # raises RepoLookupError if revision 0 is filtered or otherwise
569 # raises RepoLookupError if revision 0 is filtered or otherwise
570 # not available. If we fail to resolve, sharing is not enabled.
570 # not available. If we fail to resolve, sharing is not enabled.
571 try:
571 try:
572 rootnode = srcpeer.lookup('0')
572 rootnode = srcpeer.lookup('0')
573 if rootnode != node.nullid:
573 if rootnode != node.nullid:
574 sharepath = os.path.join(sharepool, node.hex(rootnode))
574 sharepath = os.path.join(sharepool, node.hex(rootnode))
575 else:
575 else:
576 ui.status(_('(not using pooled storage: '
576 ui.status(_('(not using pooled storage: '
577 'remote appears to be empty)\n'))
577 'remote appears to be empty)\n'))
578 except error.RepoLookupError:
578 except error.RepoLookupError:
579 ui.status(_('(not using pooled storage: '
579 ui.status(_('(not using pooled storage: '
580 'unable to resolve identity of remote)\n'))
580 'unable to resolve identity of remote)\n'))
581 elif sharenamemode == 'remote':
581 elif sharenamemode == 'remote':
582 sharepath = os.path.join(
582 sharepath = os.path.join(
583 sharepool, node.hex(hashlib.sha1(source).digest()))
583 sharepool, node.hex(hashlib.sha1(source).digest()))
584 else:
584 else:
585 raise error.Abort(_('unknown share naming mode: %s') %
585 raise error.Abort(_('unknown share naming mode: %s') %
586 sharenamemode)
586 sharenamemode)
587
587
588 if sharepath:
588 if sharepath:
589 return clonewithshare(ui, peeropts, sharepath, source, srcpeer,
589 return clonewithshare(ui, peeropts, sharepath, source, srcpeer,
590 dest, pull=pull, rev=rev, update=update,
590 dest, pull=pull, rev=revs, update=update,
591 stream=stream)
591 stream=stream)
592
592
593 srclock = destlock = cleandir = None
593 srclock = destlock = cleandir = None
594 srcrepo = srcpeer.local()
594 srcrepo = srcpeer.local()
595 try:
595 try:
596 abspath = origsource
596 abspath = origsource
597 if islocal(origsource):
597 if islocal(origsource):
598 abspath = os.path.abspath(util.urllocalpath(origsource))
598 abspath = os.path.abspath(util.urllocalpath(origsource))
599
599
600 if islocal(dest):
600 if islocal(dest):
601 cleandir = dest
601 cleandir = dest
602
602
603 copy = False
603 copy = False
604 if (srcrepo and srcrepo.cancopy() and islocal(dest)
604 if (srcrepo and srcrepo.cancopy() and islocal(dest)
605 and not phases.hassecret(srcrepo)):
605 and not phases.hassecret(srcrepo)):
606 copy = not pull and not rev
606 copy = not pull and not revs
607
607
608 if copy:
608 if copy:
609 try:
609 try:
610 # we use a lock here because if we race with commit, we
610 # we use a lock here because if we race with commit, we
611 # can end up with extra data in the cloned revlogs that's
611 # can end up with extra data in the cloned revlogs that's
612 # not pointed to by changesets, thus causing verify to
612 # not pointed to by changesets, thus causing verify to
613 # fail
613 # fail
614 srclock = srcrepo.lock(wait=False)
614 srclock = srcrepo.lock(wait=False)
615 except error.LockError:
615 except error.LockError:
616 copy = False
616 copy = False
617
617
618 if copy:
618 if copy:
619 srcrepo.hook('preoutgoing', throw=True, source='clone')
619 srcrepo.hook('preoutgoing', throw=True, source='clone')
620 hgdir = os.path.realpath(os.path.join(dest, ".hg"))
620 hgdir = os.path.realpath(os.path.join(dest, ".hg"))
621 if not os.path.exists(dest):
621 if not os.path.exists(dest):
622 os.mkdir(dest)
622 os.mkdir(dest)
623 else:
623 else:
624 # only clean up directories we create ourselves
624 # only clean up directories we create ourselves
625 cleandir = hgdir
625 cleandir = hgdir
626 try:
626 try:
627 destpath = hgdir
627 destpath = hgdir
628 util.makedir(destpath, notindexed=True)
628 util.makedir(destpath, notindexed=True)
629 except OSError as inst:
629 except OSError as inst:
630 if inst.errno == errno.EEXIST:
630 if inst.errno == errno.EEXIST:
631 cleandir = None
631 cleandir = None
632 raise error.Abort(_("destination '%s' already exists")
632 raise error.Abort(_("destination '%s' already exists")
633 % dest)
633 % dest)
634 raise
634 raise
635
635
636 destlock = copystore(ui, srcrepo, destpath)
636 destlock = copystore(ui, srcrepo, destpath)
637 # copy bookmarks over
637 # copy bookmarks over
638 srcbookmarks = srcrepo.vfs.join('bookmarks')
638 srcbookmarks = srcrepo.vfs.join('bookmarks')
639 dstbookmarks = os.path.join(destpath, 'bookmarks')
639 dstbookmarks = os.path.join(destpath, 'bookmarks')
640 if os.path.exists(srcbookmarks):
640 if os.path.exists(srcbookmarks):
641 util.copyfile(srcbookmarks, dstbookmarks)
641 util.copyfile(srcbookmarks, dstbookmarks)
642
642
643 dstcachedir = os.path.join(destpath, 'cache')
643 dstcachedir = os.path.join(destpath, 'cache')
644 for cache in cacheutil.cachetocopy(srcrepo):
644 for cache in cacheutil.cachetocopy(srcrepo):
645 _copycache(srcrepo, dstcachedir, cache)
645 _copycache(srcrepo, dstcachedir, cache)
646
646
647 # we need to re-init the repo after manually copying the data
647 # we need to re-init the repo after manually copying the data
648 # into it
648 # into it
649 destpeer = peer(srcrepo, peeropts, dest)
649 destpeer = peer(srcrepo, peeropts, dest)
650 srcrepo.hook('outgoing', source='clone',
650 srcrepo.hook('outgoing', source='clone',
651 node=node.hex(node.nullid))
651 node=node.hex(node.nullid))
652 else:
652 else:
653 try:
653 try:
654 destpeer = peer(srcrepo or ui, peeropts, dest, create=True)
654 destpeer = peer(srcrepo or ui, peeropts, dest, create=True)
655 # only pass ui when no srcrepo
655 # only pass ui when no srcrepo
656 except OSError as inst:
656 except OSError as inst:
657 if inst.errno == errno.EEXIST:
657 if inst.errno == errno.EEXIST:
658 cleandir = None
658 cleandir = None
659 raise error.Abort(_("destination '%s' already exists")
659 raise error.Abort(_("destination '%s' already exists")
660 % dest)
660 % dest)
661 raise
661 raise
662
662
663 revs = None
663 if revs:
664 if rev:
665 if not srcpeer.capable('lookup'):
664 if not srcpeer.capable('lookup'):
666 raise error.Abort(_("src repository does not support "
665 raise error.Abort(_("src repository does not support "
667 "revision lookup and so doesn't "
666 "revision lookup and so doesn't "
668 "support clone by revision"))
667 "support clone by revision"))
669 revs = [srcpeer.lookup(r) for r in rev]
668 revs = [srcpeer.lookup(r) for r in revs]
670 checkout = revs[0]
669 checkout = revs[0]
670 else:
671 revs = None
671 local = destpeer.local()
672 local = destpeer.local()
672 if local:
673 if local:
673 u = util.url(abspath)
674 u = util.url(abspath)
674 defaulturl = bytes(u)
675 defaulturl = bytes(u)
675 local.ui.setconfig('paths', 'default', defaulturl, 'clone')
676 local.ui.setconfig('paths', 'default', defaulturl, 'clone')
676 if not stream:
677 if not stream:
677 if pull:
678 if pull:
678 stream = False
679 stream = False
679 else:
680 else:
680 stream = None
681 stream = None
681 # internal config: ui.quietbookmarkmove
682 # internal config: ui.quietbookmarkmove
682 overrides = {('ui', 'quietbookmarkmove'): True}
683 overrides = {('ui', 'quietbookmarkmove'): True}
683 with local.ui.configoverride(overrides, 'clone'):
684 with local.ui.configoverride(overrides, 'clone'):
684 exchange.pull(local, srcpeer, revs,
685 exchange.pull(local, srcpeer, revs,
685 streamclonerequested=stream)
686 streamclonerequested=stream)
686 elif srcrepo:
687 elif srcrepo:
687 exchange.push(srcrepo, destpeer, revs=revs,
688 exchange.push(srcrepo, destpeer, revs=revs,
688 bookmarks=srcrepo._bookmarks.keys())
689 bookmarks=srcrepo._bookmarks.keys())
689 else:
690 else:
690 raise error.Abort(_("clone from remote to remote not supported")
691 raise error.Abort(_("clone from remote to remote not supported")
691 )
692 )
692
693
693 cleandir = None
694 cleandir = None
694
695
695 destrepo = destpeer.local()
696 destrepo = destpeer.local()
696 if destrepo:
697 if destrepo:
697 template = uimod.samplehgrcs['cloned']
698 template = uimod.samplehgrcs['cloned']
698 u = util.url(abspath)
699 u = util.url(abspath)
699 u.passwd = None
700 u.passwd = None
700 defaulturl = bytes(u)
701 defaulturl = bytes(u)
701 destrepo.vfs.write('hgrc', util.tonativeeol(template % defaulturl))
702 destrepo.vfs.write('hgrc', util.tonativeeol(template % defaulturl))
702 destrepo.ui.setconfig('paths', 'default', defaulturl, 'clone')
703 destrepo.ui.setconfig('paths', 'default', defaulturl, 'clone')
703
704
704 if ui.configbool('experimental', 'remotenames'):
705 if ui.configbool('experimental', 'remotenames'):
705 logexchange.pullremotenames(destrepo, srcpeer)
706 logexchange.pullremotenames(destrepo, srcpeer)
706
707
707 if update:
708 if update:
708 if update is not True:
709 if update is not True:
709 checkout = srcpeer.lookup(update)
710 checkout = srcpeer.lookup(update)
710 uprev = None
711 uprev = None
711 status = None
712 status = None
712 if checkout is not None:
713 if checkout is not None:
713 try:
714 try:
714 uprev = destrepo.lookup(checkout)
715 uprev = destrepo.lookup(checkout)
715 except error.RepoLookupError:
716 except error.RepoLookupError:
716 if update is not True:
717 if update is not True:
717 try:
718 try:
718 uprev = destrepo.lookup(update)
719 uprev = destrepo.lookup(update)
719 except error.RepoLookupError:
720 except error.RepoLookupError:
720 pass
721 pass
721 if uprev is None:
722 if uprev is None:
722 try:
723 try:
723 uprev = destrepo._bookmarks['@']
724 uprev = destrepo._bookmarks['@']
724 update = '@'
725 update = '@'
725 bn = destrepo[uprev].branch()
726 bn = destrepo[uprev].branch()
726 if bn == 'default':
727 if bn == 'default':
727 status = _("updating to bookmark @\n")
728 status = _("updating to bookmark @\n")
728 else:
729 else:
729 status = (_("updating to bookmark @ on branch %s\n")
730 status = (_("updating to bookmark @ on branch %s\n")
730 % bn)
731 % bn)
731 except KeyError:
732 except KeyError:
732 try:
733 try:
733 uprev = destrepo.branchtip('default')
734 uprev = destrepo.branchtip('default')
734 except error.RepoLookupError:
735 except error.RepoLookupError:
735 uprev = destrepo.lookup('tip')
736 uprev = destrepo.lookup('tip')
736 if not status:
737 if not status:
737 bn = destrepo[uprev].branch()
738 bn = destrepo[uprev].branch()
738 status = _("updating to branch %s\n") % bn
739 status = _("updating to branch %s\n") % bn
739 destrepo.ui.status(status)
740 destrepo.ui.status(status)
740 _update(destrepo, uprev)
741 _update(destrepo, uprev)
741 if update in destrepo._bookmarks:
742 if update in destrepo._bookmarks:
742 bookmarks.activate(destrepo, update)
743 bookmarks.activate(destrepo, update)
743 finally:
744 finally:
744 release(srclock, destlock)
745 release(srclock, destlock)
745 if cleandir is not None:
746 if cleandir is not None:
746 shutil.rmtree(cleandir, True)
747 shutil.rmtree(cleandir, True)
747 if srcpeer is not None:
748 if srcpeer is not None:
748 srcpeer.close()
749 srcpeer.close()
749 return srcpeer, destpeer
750 return srcpeer, destpeer
750
751
751 def _showstats(repo, stats, quietempty=False):
752 def _showstats(repo, stats, quietempty=False):
752 if quietempty and stats.isempty():
753 if quietempty and stats.isempty():
753 return
754 return
754 repo.ui.status(_("%d files updated, %d files merged, "
755 repo.ui.status(_("%d files updated, %d files merged, "
755 "%d files removed, %d files unresolved\n") % (
756 "%d files removed, %d files unresolved\n") % (
756 stats.updatedcount, stats.mergedcount,
757 stats.updatedcount, stats.mergedcount,
757 stats.removedcount, stats.unresolvedcount))
758 stats.removedcount, stats.unresolvedcount))
758
759
759 def updaterepo(repo, node, overwrite, updatecheck=None):
760 def updaterepo(repo, node, overwrite, updatecheck=None):
760 """Update the working directory to node.
761 """Update the working directory to node.
761
762
762 When overwrite is set, changes are clobbered, merged else
763 When overwrite is set, changes are clobbered, merged else
763
764
764 returns stats (see pydoc mercurial.merge.applyupdates)"""
765 returns stats (see pydoc mercurial.merge.applyupdates)"""
765 return mergemod.update(repo, node, False, overwrite,
766 return mergemod.update(repo, node, False, overwrite,
766 labels=['working copy', 'destination'],
767 labels=['working copy', 'destination'],
767 updatecheck=updatecheck)
768 updatecheck=updatecheck)
768
769
769 def update(repo, node, quietempty=False, updatecheck=None):
770 def update(repo, node, quietempty=False, updatecheck=None):
770 """update the working directory to node"""
771 """update the working directory to node"""
771 stats = updaterepo(repo, node, False, updatecheck=updatecheck)
772 stats = updaterepo(repo, node, False, updatecheck=updatecheck)
772 _showstats(repo, stats, quietempty)
773 _showstats(repo, stats, quietempty)
773 if stats.unresolvedcount:
774 if stats.unresolvedcount:
774 repo.ui.status(_("use 'hg resolve' to retry unresolved file merges\n"))
775 repo.ui.status(_("use 'hg resolve' to retry unresolved file merges\n"))
775 return stats.unresolvedcount > 0
776 return stats.unresolvedcount > 0
776
777
777 # naming conflict in clone()
778 # naming conflict in clone()
778 _update = update
779 _update = update
779
780
780 def clean(repo, node, show_stats=True, quietempty=False):
781 def clean(repo, node, show_stats=True, quietempty=False):
781 """forcibly switch the working directory to node, clobbering changes"""
782 """forcibly switch the working directory to node, clobbering changes"""
782 stats = updaterepo(repo, node, True)
783 stats = updaterepo(repo, node, True)
783 repo.vfs.unlinkpath('graftstate', ignoremissing=True)
784 repo.vfs.unlinkpath('graftstate', ignoremissing=True)
784 if show_stats:
785 if show_stats:
785 _showstats(repo, stats, quietempty)
786 _showstats(repo, stats, quietempty)
786 return stats.unresolvedcount > 0
787 return stats.unresolvedcount > 0
787
788
788 # naming conflict in updatetotally()
789 # naming conflict in updatetotally()
789 _clean = clean
790 _clean = clean
790
791
791 def updatetotally(ui, repo, checkout, brev, clean=False, updatecheck=None):
792 def updatetotally(ui, repo, checkout, brev, clean=False, updatecheck=None):
792 """Update the working directory with extra care for non-file components
793 """Update the working directory with extra care for non-file components
793
794
794 This takes care of non-file components below:
795 This takes care of non-file components below:
795
796
796 :bookmark: might be advanced or (in)activated
797 :bookmark: might be advanced or (in)activated
797
798
798 This takes arguments below:
799 This takes arguments below:
799
800
800 :checkout: to which revision the working directory is updated
801 :checkout: to which revision the working directory is updated
801 :brev: a name, which might be a bookmark to be activated after updating
802 :brev: a name, which might be a bookmark to be activated after updating
802 :clean: whether changes in the working directory can be discarded
803 :clean: whether changes in the working directory can be discarded
803 :updatecheck: how to deal with a dirty working directory
804 :updatecheck: how to deal with a dirty working directory
804
805
805 Valid values for updatecheck are (None => linear):
806 Valid values for updatecheck are (None => linear):
806
807
807 * abort: abort if the working directory is dirty
808 * abort: abort if the working directory is dirty
808 * none: don't check (merge working directory changes into destination)
809 * none: don't check (merge working directory changes into destination)
809 * linear: check that update is linear before merging working directory
810 * linear: check that update is linear before merging working directory
810 changes into destination
811 changes into destination
811 * noconflict: check that the update does not result in file merges
812 * noconflict: check that the update does not result in file merges
812
813
813 This returns whether conflict is detected at updating or not.
814 This returns whether conflict is detected at updating or not.
814 """
815 """
815 if updatecheck is None:
816 if updatecheck is None:
816 updatecheck = ui.config('commands', 'update.check')
817 updatecheck = ui.config('commands', 'update.check')
817 if updatecheck not in ('abort', 'none', 'linear', 'noconflict'):
818 if updatecheck not in ('abort', 'none', 'linear', 'noconflict'):
818 # If not configured, or invalid value configured
819 # If not configured, or invalid value configured
819 updatecheck = 'linear'
820 updatecheck = 'linear'
820 with repo.wlock():
821 with repo.wlock():
821 movemarkfrom = None
822 movemarkfrom = None
822 warndest = False
823 warndest = False
823 if checkout is None:
824 if checkout is None:
824 updata = destutil.destupdate(repo, clean=clean)
825 updata = destutil.destupdate(repo, clean=clean)
825 checkout, movemarkfrom, brev = updata
826 checkout, movemarkfrom, brev = updata
826 warndest = True
827 warndest = True
827
828
828 if clean:
829 if clean:
829 ret = _clean(repo, checkout)
830 ret = _clean(repo, checkout)
830 else:
831 else:
831 if updatecheck == 'abort':
832 if updatecheck == 'abort':
832 cmdutil.bailifchanged(repo, merge=False)
833 cmdutil.bailifchanged(repo, merge=False)
833 updatecheck = 'none'
834 updatecheck = 'none'
834 ret = _update(repo, checkout, updatecheck=updatecheck)
835 ret = _update(repo, checkout, updatecheck=updatecheck)
835
836
836 if not ret and movemarkfrom:
837 if not ret and movemarkfrom:
837 if movemarkfrom == repo['.'].node():
838 if movemarkfrom == repo['.'].node():
838 pass # no-op update
839 pass # no-op update
839 elif bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
840 elif bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
840 b = ui.label(repo._activebookmark, 'bookmarks.active')
841 b = ui.label(repo._activebookmark, 'bookmarks.active')
841 ui.status(_("updating bookmark %s\n") % b)
842 ui.status(_("updating bookmark %s\n") % b)
842 else:
843 else:
843 # this can happen with a non-linear update
844 # this can happen with a non-linear update
844 b = ui.label(repo._activebookmark, 'bookmarks')
845 b = ui.label(repo._activebookmark, 'bookmarks')
845 ui.status(_("(leaving bookmark %s)\n") % b)
846 ui.status(_("(leaving bookmark %s)\n") % b)
846 bookmarks.deactivate(repo)
847 bookmarks.deactivate(repo)
847 elif brev in repo._bookmarks:
848 elif brev in repo._bookmarks:
848 if brev != repo._activebookmark:
849 if brev != repo._activebookmark:
849 b = ui.label(brev, 'bookmarks.active')
850 b = ui.label(brev, 'bookmarks.active')
850 ui.status(_("(activating bookmark %s)\n") % b)
851 ui.status(_("(activating bookmark %s)\n") % b)
851 bookmarks.activate(repo, brev)
852 bookmarks.activate(repo, brev)
852 elif brev:
853 elif brev:
853 if repo._activebookmark:
854 if repo._activebookmark:
854 b = ui.label(repo._activebookmark, 'bookmarks')
855 b = ui.label(repo._activebookmark, 'bookmarks')
855 ui.status(_("(leaving bookmark %s)\n") % b)
856 ui.status(_("(leaving bookmark %s)\n") % b)
856 bookmarks.deactivate(repo)
857 bookmarks.deactivate(repo)
857
858
858 if warndest:
859 if warndest:
859 destutil.statusotherdests(ui, repo)
860 destutil.statusotherdests(ui, repo)
860
861
861 return ret
862 return ret
862
863
863 def merge(repo, node, force=None, remind=True, mergeforce=False, labels=None,
864 def merge(repo, node, force=None, remind=True, mergeforce=False, labels=None,
864 abort=False):
865 abort=False):
865 """Branch merge with node, resolving changes. Return true if any
866 """Branch merge with node, resolving changes. Return true if any
866 unresolved conflicts."""
867 unresolved conflicts."""
867 if not abort:
868 if not abort:
868 stats = mergemod.update(repo, node, True, force, mergeforce=mergeforce,
869 stats = mergemod.update(repo, node, True, force, mergeforce=mergeforce,
869 labels=labels)
870 labels=labels)
870 else:
871 else:
871 ms = mergemod.mergestate.read(repo)
872 ms = mergemod.mergestate.read(repo)
872 if ms.active():
873 if ms.active():
873 # there were conflicts
874 # there were conflicts
874 node = ms.localctx.hex()
875 node = ms.localctx.hex()
875 else:
876 else:
876 # there were no conficts, mergestate was not stored
877 # there were no conficts, mergestate was not stored
877 node = repo['.'].hex()
878 node = repo['.'].hex()
878
879
879 repo.ui.status(_("aborting the merge, updating back to"
880 repo.ui.status(_("aborting the merge, updating back to"
880 " %s\n") % node[:12])
881 " %s\n") % node[:12])
881 stats = mergemod.update(repo, node, branchmerge=False, force=True,
882 stats = mergemod.update(repo, node, branchmerge=False, force=True,
882 labels=labels)
883 labels=labels)
883
884
884 _showstats(repo, stats)
885 _showstats(repo, stats)
885 if stats.unresolvedcount:
886 if stats.unresolvedcount:
886 repo.ui.status(_("use 'hg resolve' to retry unresolved file merges "
887 repo.ui.status(_("use 'hg resolve' to retry unresolved file merges "
887 "or 'hg merge --abort' to abandon\n"))
888 "or 'hg merge --abort' to abandon\n"))
888 elif remind and not abort:
889 elif remind and not abort:
889 repo.ui.status(_("(branch merge, don't forget to commit)\n"))
890 repo.ui.status(_("(branch merge, don't forget to commit)\n"))
890 return stats.unresolvedcount > 0
891 return stats.unresolvedcount > 0
891
892
892 def _incoming(displaychlist, subreporecurse, ui, repo, source,
893 def _incoming(displaychlist, subreporecurse, ui, repo, source,
893 opts, buffered=False):
894 opts, buffered=False):
894 """
895 """
895 Helper for incoming / gincoming.
896 Helper for incoming / gincoming.
896 displaychlist gets called with
897 displaychlist gets called with
897 (remoterepo, incomingchangesetlist, displayer) parameters,
898 (remoterepo, incomingchangesetlist, displayer) parameters,
898 and is supposed to contain only code that can't be unified.
899 and is supposed to contain only code that can't be unified.
899 """
900 """
900 source, branches = parseurl(ui.expandpath(source), opts.get('branch'))
901 source, branches = parseurl(ui.expandpath(source), opts.get('branch'))
901 other = peer(repo, opts, source)
902 other = peer(repo, opts, source)
902 ui.status(_('comparing with %s\n') % util.hidepassword(source))
903 ui.status(_('comparing with %s\n') % util.hidepassword(source))
903 revs, checkout = addbranchrevs(repo, other, branches, opts.get('rev'))
904 revs, checkout = addbranchrevs(repo, other, branches, opts.get('rev'))
904
905
905 if revs:
906 if revs:
906 revs = [other.lookup(rev) for rev in revs]
907 revs = [other.lookup(rev) for rev in revs]
907 other, chlist, cleanupfn = bundlerepo.getremotechanges(ui, repo, other,
908 other, chlist, cleanupfn = bundlerepo.getremotechanges(ui, repo, other,
908 revs, opts["bundle"], opts["force"])
909 revs, opts["bundle"], opts["force"])
909 try:
910 try:
910 if not chlist:
911 if not chlist:
911 ui.status(_("no changes found\n"))
912 ui.status(_("no changes found\n"))
912 return subreporecurse()
913 return subreporecurse()
913 ui.pager('incoming')
914 ui.pager('incoming')
914 displayer = logcmdutil.changesetdisplayer(ui, other, opts,
915 displayer = logcmdutil.changesetdisplayer(ui, other, opts,
915 buffered=buffered)
916 buffered=buffered)
916 displaychlist(other, chlist, displayer)
917 displaychlist(other, chlist, displayer)
917 displayer.close()
918 displayer.close()
918 finally:
919 finally:
919 cleanupfn()
920 cleanupfn()
920 subreporecurse()
921 subreporecurse()
921 return 0 # exit code is zero since we found incoming changes
922 return 0 # exit code is zero since we found incoming changes
922
923
923 def incoming(ui, repo, source, opts):
924 def incoming(ui, repo, source, opts):
924 def subreporecurse():
925 def subreporecurse():
925 ret = 1
926 ret = 1
926 if opts.get('subrepos'):
927 if opts.get('subrepos'):
927 ctx = repo[None]
928 ctx = repo[None]
928 for subpath in sorted(ctx.substate):
929 for subpath in sorted(ctx.substate):
929 sub = ctx.sub(subpath)
930 sub = ctx.sub(subpath)
930 ret = min(ret, sub.incoming(ui, source, opts))
931 ret = min(ret, sub.incoming(ui, source, opts))
931 return ret
932 return ret
932
933
933 def display(other, chlist, displayer):
934 def display(other, chlist, displayer):
934 limit = logcmdutil.getlimit(opts)
935 limit = logcmdutil.getlimit(opts)
935 if opts.get('newest_first'):
936 if opts.get('newest_first'):
936 chlist.reverse()
937 chlist.reverse()
937 count = 0
938 count = 0
938 for n in chlist:
939 for n in chlist:
939 if limit is not None and count >= limit:
940 if limit is not None and count >= limit:
940 break
941 break
941 parents = [p for p in other.changelog.parents(n) if p != nullid]
942 parents = [p for p in other.changelog.parents(n) if p != nullid]
942 if opts.get('no_merges') and len(parents) == 2:
943 if opts.get('no_merges') and len(parents) == 2:
943 continue
944 continue
944 count += 1
945 count += 1
945 displayer.show(other[n])
946 displayer.show(other[n])
946 return _incoming(display, subreporecurse, ui, repo, source, opts)
947 return _incoming(display, subreporecurse, ui, repo, source, opts)
947
948
948 def _outgoing(ui, repo, dest, opts):
949 def _outgoing(ui, repo, dest, opts):
949 path = ui.paths.getpath(dest, default=('default-push', 'default'))
950 path = ui.paths.getpath(dest, default=('default-push', 'default'))
950 if not path:
951 if not path:
951 raise error.Abort(_('default repository not configured!'),
952 raise error.Abort(_('default repository not configured!'),
952 hint=_("see 'hg help config.paths'"))
953 hint=_("see 'hg help config.paths'"))
953 dest = path.pushloc or path.loc
954 dest = path.pushloc or path.loc
954 branches = path.branch, opts.get('branch') or []
955 branches = path.branch, opts.get('branch') or []
955
956
956 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
957 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
957 revs, checkout = addbranchrevs(repo, repo, branches, opts.get('rev'))
958 revs, checkout = addbranchrevs(repo, repo, branches, opts.get('rev'))
958 if revs:
959 if revs:
959 revs = [repo.lookup(rev) for rev in scmutil.revrange(repo, revs)]
960 revs = [repo.lookup(rev) for rev in scmutil.revrange(repo, revs)]
960
961
961 other = peer(repo, opts, dest)
962 other = peer(repo, opts, dest)
962 outgoing = discovery.findcommonoutgoing(repo, other, revs,
963 outgoing = discovery.findcommonoutgoing(repo, other, revs,
963 force=opts.get('force'))
964 force=opts.get('force'))
964 o = outgoing.missing
965 o = outgoing.missing
965 if not o:
966 if not o:
966 scmutil.nochangesfound(repo.ui, repo, outgoing.excluded)
967 scmutil.nochangesfound(repo.ui, repo, outgoing.excluded)
967 return o, other
968 return o, other
968
969
969 def outgoing(ui, repo, dest, opts):
970 def outgoing(ui, repo, dest, opts):
970 def recurse():
971 def recurse():
971 ret = 1
972 ret = 1
972 if opts.get('subrepos'):
973 if opts.get('subrepos'):
973 ctx = repo[None]
974 ctx = repo[None]
974 for subpath in sorted(ctx.substate):
975 for subpath in sorted(ctx.substate):
975 sub = ctx.sub(subpath)
976 sub = ctx.sub(subpath)
976 ret = min(ret, sub.outgoing(ui, dest, opts))
977 ret = min(ret, sub.outgoing(ui, dest, opts))
977 return ret
978 return ret
978
979
979 limit = logcmdutil.getlimit(opts)
980 limit = logcmdutil.getlimit(opts)
980 o, other = _outgoing(ui, repo, dest, opts)
981 o, other = _outgoing(ui, repo, dest, opts)
981 if not o:
982 if not o:
982 cmdutil.outgoinghooks(ui, repo, other, opts, o)
983 cmdutil.outgoinghooks(ui, repo, other, opts, o)
983 return recurse()
984 return recurse()
984
985
985 if opts.get('newest_first'):
986 if opts.get('newest_first'):
986 o.reverse()
987 o.reverse()
987 ui.pager('outgoing')
988 ui.pager('outgoing')
988 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
989 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
989 count = 0
990 count = 0
990 for n in o:
991 for n in o:
991 if limit is not None and count >= limit:
992 if limit is not None and count >= limit:
992 break
993 break
993 parents = [p for p in repo.changelog.parents(n) if p != nullid]
994 parents = [p for p in repo.changelog.parents(n) if p != nullid]
994 if opts.get('no_merges') and len(parents) == 2:
995 if opts.get('no_merges') and len(parents) == 2:
995 continue
996 continue
996 count += 1
997 count += 1
997 displayer.show(repo[n])
998 displayer.show(repo[n])
998 displayer.close()
999 displayer.close()
999 cmdutil.outgoinghooks(ui, repo, other, opts, o)
1000 cmdutil.outgoinghooks(ui, repo, other, opts, o)
1000 recurse()
1001 recurse()
1001 return 0 # exit code is zero since we found outgoing changes
1002 return 0 # exit code is zero since we found outgoing changes
1002
1003
1003 def verify(repo):
1004 def verify(repo):
1004 """verify the consistency of a repository"""
1005 """verify the consistency of a repository"""
1005 ret = verifymod.verify(repo)
1006 ret = verifymod.verify(repo)
1006
1007
1007 # Broken subrepo references in hidden csets don't seem worth worrying about,
1008 # Broken subrepo references in hidden csets don't seem worth worrying about,
1008 # since they can't be pushed/pulled, and --hidden can be used if they are a
1009 # since they can't be pushed/pulled, and --hidden can be used if they are a
1009 # concern.
1010 # concern.
1010
1011
1011 # pathto() is needed for -R case
1012 # pathto() is needed for -R case
1012 revs = repo.revs("filelog(%s)",
1013 revs = repo.revs("filelog(%s)",
1013 util.pathto(repo.root, repo.getcwd(), '.hgsubstate'))
1014 util.pathto(repo.root, repo.getcwd(), '.hgsubstate'))
1014
1015
1015 if revs:
1016 if revs:
1016 repo.ui.status(_('checking subrepo links\n'))
1017 repo.ui.status(_('checking subrepo links\n'))
1017 for rev in revs:
1018 for rev in revs:
1018 ctx = repo[rev]
1019 ctx = repo[rev]
1019 try:
1020 try:
1020 for subpath in ctx.substate:
1021 for subpath in ctx.substate:
1021 try:
1022 try:
1022 ret = (ctx.sub(subpath, allowcreate=False).verify()
1023 ret = (ctx.sub(subpath, allowcreate=False).verify()
1023 or ret)
1024 or ret)
1024 except error.RepoError as e:
1025 except error.RepoError as e:
1025 repo.ui.warn(('%s: %s\n') % (rev, e))
1026 repo.ui.warn(('%s: %s\n') % (rev, e))
1026 except Exception:
1027 except Exception:
1027 repo.ui.warn(_('.hgsubstate is corrupt in revision %s\n') %
1028 repo.ui.warn(_('.hgsubstate is corrupt in revision %s\n') %
1028 node.short(ctx.node()))
1029 node.short(ctx.node()))
1029
1030
1030 return ret
1031 return ret
1031
1032
1032 def remoteui(src, opts):
1033 def remoteui(src, opts):
1033 'build a remote ui from ui or repo and opts'
1034 'build a remote ui from ui or repo and opts'
1034 if util.safehasattr(src, 'baseui'): # looks like a repository
1035 if util.safehasattr(src, 'baseui'): # looks like a repository
1035 dst = src.baseui.copy() # drop repo-specific config
1036 dst = src.baseui.copy() # drop repo-specific config
1036 src = src.ui # copy target options from repo
1037 src = src.ui # copy target options from repo
1037 else: # assume it's a global ui object
1038 else: # assume it's a global ui object
1038 dst = src.copy() # keep all global options
1039 dst = src.copy() # keep all global options
1039
1040
1040 # copy ssh-specific options
1041 # copy ssh-specific options
1041 for o in 'ssh', 'remotecmd':
1042 for o in 'ssh', 'remotecmd':
1042 v = opts.get(o) or src.config('ui', o)
1043 v = opts.get(o) or src.config('ui', o)
1043 if v:
1044 if v:
1044 dst.setconfig("ui", o, v, 'copied')
1045 dst.setconfig("ui", o, v, 'copied')
1045
1046
1046 # copy bundle-specific options
1047 # copy bundle-specific options
1047 r = src.config('bundle', 'mainreporoot')
1048 r = src.config('bundle', 'mainreporoot')
1048 if r:
1049 if r:
1049 dst.setconfig('bundle', 'mainreporoot', r, 'copied')
1050 dst.setconfig('bundle', 'mainreporoot', r, 'copied')
1050
1051
1051 # copy selected local settings to the remote ui
1052 # copy selected local settings to the remote ui
1052 for sect in ('auth', 'hostfingerprints', 'hostsecurity', 'http_proxy'):
1053 for sect in ('auth', 'hostfingerprints', 'hostsecurity', 'http_proxy'):
1053 for key, val in src.configitems(sect):
1054 for key, val in src.configitems(sect):
1054 dst.setconfig(sect, key, val, 'copied')
1055 dst.setconfig(sect, key, val, 'copied')
1055 v = src.config('web', 'cacerts')
1056 v = src.config('web', 'cacerts')
1056 if v:
1057 if v:
1057 dst.setconfig('web', 'cacerts', util.expandpath(v), 'copied')
1058 dst.setconfig('web', 'cacerts', util.expandpath(v), 'copied')
1058
1059
1059 return dst
1060 return dst
1060
1061
1061 # Files of interest
1062 # Files of interest
1062 # Used to check if the repository has changed looking at mtime and size of
1063 # Used to check if the repository has changed looking at mtime and size of
1063 # these files.
1064 # these files.
1064 foi = [('spath', '00changelog.i'),
1065 foi = [('spath', '00changelog.i'),
1065 ('spath', 'phaseroots'), # ! phase can change content at the same size
1066 ('spath', 'phaseroots'), # ! phase can change content at the same size
1066 ('spath', 'obsstore'),
1067 ('spath', 'obsstore'),
1067 ('path', 'bookmarks'), # ! bookmark can change content at the same size
1068 ('path', 'bookmarks'), # ! bookmark can change content at the same size
1068 ]
1069 ]
1069
1070
1070 class cachedlocalrepo(object):
1071 class cachedlocalrepo(object):
1071 """Holds a localrepository that can be cached and reused."""
1072 """Holds a localrepository that can be cached and reused."""
1072
1073
1073 def __init__(self, repo):
1074 def __init__(self, repo):
1074 """Create a new cached repo from an existing repo.
1075 """Create a new cached repo from an existing repo.
1075
1076
1076 We assume the passed in repo was recently created. If the
1077 We assume the passed in repo was recently created. If the
1077 repo has changed between when it was created and when it was
1078 repo has changed between when it was created and when it was
1078 turned into a cache, it may not refresh properly.
1079 turned into a cache, it may not refresh properly.
1079 """
1080 """
1080 assert isinstance(repo, localrepo.localrepository)
1081 assert isinstance(repo, localrepo.localrepository)
1081 self._repo = repo
1082 self._repo = repo
1082 self._state, self.mtime = self._repostate()
1083 self._state, self.mtime = self._repostate()
1083 self._filtername = repo.filtername
1084 self._filtername = repo.filtername
1084
1085
1085 def fetch(self):
1086 def fetch(self):
1086 """Refresh (if necessary) and return a repository.
1087 """Refresh (if necessary) and return a repository.
1087
1088
1088 If the cached instance is out of date, it will be recreated
1089 If the cached instance is out of date, it will be recreated
1089 automatically and returned.
1090 automatically and returned.
1090
1091
1091 Returns a tuple of the repo and a boolean indicating whether a new
1092 Returns a tuple of the repo and a boolean indicating whether a new
1092 repo instance was created.
1093 repo instance was created.
1093 """
1094 """
1094 # We compare the mtimes and sizes of some well-known files to
1095 # We compare the mtimes and sizes of some well-known files to
1095 # determine if the repo changed. This is not precise, as mtimes
1096 # determine if the repo changed. This is not precise, as mtimes
1096 # are susceptible to clock skew and imprecise filesystems and
1097 # are susceptible to clock skew and imprecise filesystems and
1097 # file content can change while maintaining the same size.
1098 # file content can change while maintaining the same size.
1098
1099
1099 state, mtime = self._repostate()
1100 state, mtime = self._repostate()
1100 if state == self._state:
1101 if state == self._state:
1101 return self._repo, False
1102 return self._repo, False
1102
1103
1103 repo = repository(self._repo.baseui, self._repo.url())
1104 repo = repository(self._repo.baseui, self._repo.url())
1104 if self._filtername:
1105 if self._filtername:
1105 self._repo = repo.filtered(self._filtername)
1106 self._repo = repo.filtered(self._filtername)
1106 else:
1107 else:
1107 self._repo = repo.unfiltered()
1108 self._repo = repo.unfiltered()
1108 self._state = state
1109 self._state = state
1109 self.mtime = mtime
1110 self.mtime = mtime
1110
1111
1111 return self._repo, True
1112 return self._repo, True
1112
1113
1113 def _repostate(self):
1114 def _repostate(self):
1114 state = []
1115 state = []
1115 maxmtime = -1
1116 maxmtime = -1
1116 for attr, fname in foi:
1117 for attr, fname in foi:
1117 prefix = getattr(self._repo, attr)
1118 prefix = getattr(self._repo, attr)
1118 p = os.path.join(prefix, fname)
1119 p = os.path.join(prefix, fname)
1119 try:
1120 try:
1120 st = os.stat(p)
1121 st = os.stat(p)
1121 except OSError:
1122 except OSError:
1122 st = os.stat(prefix)
1123 st = os.stat(prefix)
1123 state.append((st[stat.ST_MTIME], st.st_size))
1124 state.append((st[stat.ST_MTIME], st.st_size))
1124 maxmtime = max(maxmtime, st[stat.ST_MTIME])
1125 maxmtime = max(maxmtime, st[stat.ST_MTIME])
1125
1126
1126 return tuple(state), maxmtime
1127 return tuple(state), maxmtime
1127
1128
1128 def copy(self):
1129 def copy(self):
1129 """Obtain a copy of this class instance.
1130 """Obtain a copy of this class instance.
1130
1131
1131 A new localrepository instance is obtained. The new instance should be
1132 A new localrepository instance is obtained. The new instance should be
1132 completely independent of the original.
1133 completely independent of the original.
1133 """
1134 """
1134 repo = repository(self._repo.baseui, self._repo.origroot)
1135 repo = repository(self._repo.baseui, self._repo.origroot)
1135 if self._filtername:
1136 if self._filtername:
1136 repo = repo.filtered(self._filtername)
1137 repo = repo.filtered(self._filtername)
1137 else:
1138 else:
1138 repo = repo.unfiltered()
1139 repo = repo.unfiltered()
1139 c = cachedlocalrepo(repo)
1140 c = cachedlocalrepo(repo)
1140 c._state = self._state
1141 c._state = self._state
1141 c.mtime = self.mtime
1142 c.mtime = self.mtime
1142 return c
1143 return c
General Comments 0
You need to be logged in to leave comments. Login now