##// END OF EJS Templates
mq: drop the use of `dirstate.merged`...
marmoute -
r48543:8c73818c default
parent child Browse files
Show More
@@ -1,4318 +1,4309 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 import sys
71 import sys
72 from mercurial.i18n import _
72 from mercurial.i18n import _
73 from mercurial.node import (
73 from mercurial.node import (
74 bin,
74 bin,
75 hex,
75 hex,
76 nullrev,
76 nullrev,
77 short,
77 short,
78 )
78 )
79 from mercurial.pycompat import (
79 from mercurial.pycompat import (
80 delattr,
80 delattr,
81 getattr,
81 getattr,
82 open,
82 open,
83 )
83 )
84 from mercurial import (
84 from mercurial import (
85 cmdutil,
85 cmdutil,
86 commands,
86 commands,
87 dirstateguard,
87 dirstateguard,
88 encoding,
88 encoding,
89 error,
89 error,
90 extensions,
90 extensions,
91 hg,
91 hg,
92 localrepo,
92 localrepo,
93 lock as lockmod,
93 lock as lockmod,
94 logcmdutil,
94 logcmdutil,
95 patch as patchmod,
95 patch as patchmod,
96 phases,
96 phases,
97 pycompat,
97 pycompat,
98 registrar,
98 registrar,
99 revsetlang,
99 revsetlang,
100 scmutil,
100 scmutil,
101 smartset,
101 smartset,
102 strip,
102 strip,
103 subrepoutil,
103 subrepoutil,
104 util,
104 util,
105 vfs as vfsmod,
105 vfs as vfsmod,
106 )
106 )
107 from mercurial.utils import (
107 from mercurial.utils import (
108 dateutil,
108 dateutil,
109 stringutil,
109 stringutil,
110 urlutil,
110 urlutil,
111 )
111 )
112
112
113 release = lockmod.release
113 release = lockmod.release
114 seriesopts = [(b's', b'summary', None, _(b'print first line of patch header'))]
114 seriesopts = [(b's', b'summary', None, _(b'print first line of patch header'))]
115
115
116 cmdtable = {}
116 cmdtable = {}
117 command = registrar.command(cmdtable)
117 command = registrar.command(cmdtable)
118 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
118 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
119 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
119 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
120 # be specifying the version(s) of Mercurial they are tested with, or
120 # be specifying the version(s) of Mercurial they are tested with, or
121 # leave the attribute unspecified.
121 # leave the attribute unspecified.
122 testedwith = b'ships-with-hg-core'
122 testedwith = b'ships-with-hg-core'
123
123
124 configtable = {}
124 configtable = {}
125 configitem = registrar.configitem(configtable)
125 configitem = registrar.configitem(configtable)
126
126
127 configitem(
127 configitem(
128 b'mq',
128 b'mq',
129 b'git',
129 b'git',
130 default=b'auto',
130 default=b'auto',
131 )
131 )
132 configitem(
132 configitem(
133 b'mq',
133 b'mq',
134 b'keepchanges',
134 b'keepchanges',
135 default=False,
135 default=False,
136 )
136 )
137 configitem(
137 configitem(
138 b'mq',
138 b'mq',
139 b'plain',
139 b'plain',
140 default=False,
140 default=False,
141 )
141 )
142 configitem(
142 configitem(
143 b'mq',
143 b'mq',
144 b'secret',
144 b'secret',
145 default=False,
145 default=False,
146 )
146 )
147
147
148 # force load strip extension formerly included in mq and import some utility
148 # force load strip extension formerly included in mq and import some utility
149 try:
149 try:
150 extensions.find(b'strip')
150 extensions.find(b'strip')
151 except KeyError:
151 except KeyError:
152 # note: load is lazy so we could avoid the try-except,
152 # note: load is lazy so we could avoid the try-except,
153 # but I (marmoute) prefer this explicit code.
153 # but I (marmoute) prefer this explicit code.
154 class dummyui(object):
154 class dummyui(object):
155 def debug(self, msg):
155 def debug(self, msg):
156 pass
156 pass
157
157
158 def log(self, event, msgfmt, *msgargs, **opts):
158 def log(self, event, msgfmt, *msgargs, **opts):
159 pass
159 pass
160
160
161 extensions.load(dummyui(), b'strip', b'')
161 extensions.load(dummyui(), b'strip', b'')
162
162
163 strip = strip.strip
163 strip = strip.strip
164
164
165
165
166 def checksubstate(repo, baserev=None):
166 def checksubstate(repo, baserev=None):
167 """return list of subrepos at a different revision than substate.
167 """return list of subrepos at a different revision than substate.
168 Abort if any subrepos have uncommitted changes."""
168 Abort if any subrepos have uncommitted changes."""
169 inclsubs = []
169 inclsubs = []
170 wctx = repo[None]
170 wctx = repo[None]
171 if baserev:
171 if baserev:
172 bctx = repo[baserev]
172 bctx = repo[baserev]
173 else:
173 else:
174 bctx = wctx.p1()
174 bctx = wctx.p1()
175 for s in sorted(wctx.substate):
175 for s in sorted(wctx.substate):
176 wctx.sub(s).bailifchanged(True)
176 wctx.sub(s).bailifchanged(True)
177 if s not in bctx.substate or bctx.sub(s).dirty():
177 if s not in bctx.substate or bctx.sub(s).dirty():
178 inclsubs.append(s)
178 inclsubs.append(s)
179 return inclsubs
179 return inclsubs
180
180
181
181
182 # Patch names looks like unix-file names.
182 # Patch names looks like unix-file names.
183 # They must be joinable with queue directory and result in the patch path.
183 # They must be joinable with queue directory and result in the patch path.
184 normname = util.normpath
184 normname = util.normpath
185
185
186
186
187 class statusentry(object):
187 class statusentry(object):
188 def __init__(self, node, name):
188 def __init__(self, node, name):
189 self.node, self.name = node, name
189 self.node, self.name = node, name
190
190
191 def __bytes__(self):
191 def __bytes__(self):
192 return hex(self.node) + b':' + self.name
192 return hex(self.node) + b':' + self.name
193
193
194 __str__ = encoding.strmethod(__bytes__)
194 __str__ = encoding.strmethod(__bytes__)
195 __repr__ = encoding.strmethod(__bytes__)
195 __repr__ = encoding.strmethod(__bytes__)
196
196
197
197
198 # The order of the headers in 'hg export' HG patches:
198 # The order of the headers in 'hg export' HG patches:
199 HGHEADERS = [
199 HGHEADERS = [
200 # '# HG changeset patch',
200 # '# HG changeset patch',
201 b'# User ',
201 b'# User ',
202 b'# Date ',
202 b'# Date ',
203 b'# ',
203 b'# ',
204 b'# Branch ',
204 b'# Branch ',
205 b'# Node ID ',
205 b'# Node ID ',
206 b'# Parent ', # can occur twice for merges - but that is not relevant for mq
206 b'# Parent ', # can occur twice for merges - but that is not relevant for mq
207 ]
207 ]
208 # The order of headers in plain 'mail style' patches:
208 # The order of headers in plain 'mail style' patches:
209 PLAINHEADERS = {
209 PLAINHEADERS = {
210 b'from': 0,
210 b'from': 0,
211 b'date': 1,
211 b'date': 1,
212 b'subject': 2,
212 b'subject': 2,
213 }
213 }
214
214
215
215
216 def inserthgheader(lines, header, value):
216 def inserthgheader(lines, header, value):
217 """Assuming lines contains a HG patch header, add a header line with value.
217 """Assuming lines contains a HG patch header, add a header line with value.
218 >>> try: inserthgheader([], b'# Date ', b'z')
218 >>> try: inserthgheader([], b'# Date ', b'z')
219 ... except ValueError as inst: print("oops")
219 ... except ValueError as inst: print("oops")
220 oops
220 oops
221 >>> inserthgheader([b'# HG changeset patch'], b'# Date ', b'z')
221 >>> inserthgheader([b'# HG changeset patch'], b'# Date ', b'z')
222 ['# HG changeset patch', '# Date z']
222 ['# HG changeset patch', '# Date z']
223 >>> inserthgheader([b'# HG changeset patch', b''], b'# Date ', b'z')
223 >>> inserthgheader([b'# HG changeset patch', b''], b'# Date ', b'z')
224 ['# HG changeset patch', '# Date z', '']
224 ['# HG changeset patch', '# Date z', '']
225 >>> inserthgheader([b'# HG changeset patch', b'# User y'], b'# Date ', b'z')
225 >>> inserthgheader([b'# HG changeset patch', b'# User y'], b'# Date ', b'z')
226 ['# HG changeset patch', '# User y', '# Date z']
226 ['# HG changeset patch', '# User y', '# Date z']
227 >>> inserthgheader([b'# HG changeset patch', b'# Date x', b'# User y'],
227 >>> inserthgheader([b'# HG changeset patch', b'# Date x', b'# User y'],
228 ... b'# User ', b'z')
228 ... b'# User ', b'z')
229 ['# HG changeset patch', '# Date x', '# User z']
229 ['# HG changeset patch', '# Date x', '# User z']
230 >>> inserthgheader([b'# HG changeset patch', b'# Date y'], b'# Date ', b'z')
230 >>> inserthgheader([b'# HG changeset patch', b'# Date y'], b'# Date ', b'z')
231 ['# HG changeset patch', '# Date z']
231 ['# HG changeset patch', '# Date z']
232 >>> inserthgheader([b'# HG changeset patch', b'', b'# Date y'],
232 >>> inserthgheader([b'# HG changeset patch', b'', b'# Date y'],
233 ... b'# Date ', b'z')
233 ... b'# Date ', b'z')
234 ['# HG changeset patch', '# Date z', '', '# Date y']
234 ['# HG changeset patch', '# Date z', '', '# Date y']
235 >>> inserthgheader([b'# HG changeset patch', b'# Parent y'],
235 >>> inserthgheader([b'# HG changeset patch', b'# Parent y'],
236 ... b'# Date ', b'z')
236 ... b'# Date ', b'z')
237 ['# HG changeset patch', '# Date z', '# Parent y']
237 ['# HG changeset patch', '# Date z', '# Parent y']
238 """
238 """
239 start = lines.index(b'# HG changeset patch') + 1
239 start = lines.index(b'# HG changeset patch') + 1
240 newindex = HGHEADERS.index(header)
240 newindex = HGHEADERS.index(header)
241 bestpos = len(lines)
241 bestpos = len(lines)
242 for i in range(start, len(lines)):
242 for i in range(start, len(lines)):
243 line = lines[i]
243 line = lines[i]
244 if not line.startswith(b'# '):
244 if not line.startswith(b'# '):
245 bestpos = min(bestpos, i)
245 bestpos = min(bestpos, i)
246 break
246 break
247 for lineindex, h in enumerate(HGHEADERS):
247 for lineindex, h in enumerate(HGHEADERS):
248 if line.startswith(h):
248 if line.startswith(h):
249 if lineindex == newindex:
249 if lineindex == newindex:
250 lines[i] = header + value
250 lines[i] = header + value
251 return lines
251 return lines
252 if lineindex > newindex:
252 if lineindex > newindex:
253 bestpos = min(bestpos, i)
253 bestpos = min(bestpos, i)
254 break # next line
254 break # next line
255 lines.insert(bestpos, header + value)
255 lines.insert(bestpos, header + value)
256 return lines
256 return lines
257
257
258
258
259 def insertplainheader(lines, header, value):
259 def insertplainheader(lines, header, value):
260 """For lines containing a plain patch header, add a header line with value.
260 """For lines containing a plain patch header, add a header line with value.
261 >>> insertplainheader([], b'Date', b'z')
261 >>> insertplainheader([], b'Date', b'z')
262 ['Date: z']
262 ['Date: z']
263 >>> insertplainheader([b''], b'Date', b'z')
263 >>> insertplainheader([b''], b'Date', b'z')
264 ['Date: z', '']
264 ['Date: z', '']
265 >>> insertplainheader([b'x'], b'Date', b'z')
265 >>> insertplainheader([b'x'], b'Date', b'z')
266 ['Date: z', '', 'x']
266 ['Date: z', '', 'x']
267 >>> insertplainheader([b'From: y', b'x'], b'Date', b'z')
267 >>> insertplainheader([b'From: y', b'x'], b'Date', b'z')
268 ['From: y', 'Date: z', '', 'x']
268 ['From: y', 'Date: z', '', 'x']
269 >>> insertplainheader([b' date : x', b' from : y', b''], b'From', b'z')
269 >>> insertplainheader([b' date : x', b' from : y', b''], b'From', b'z')
270 [' date : x', 'From: z', '']
270 [' date : x', 'From: z', '']
271 >>> insertplainheader([b'', b'Date: y'], b'Date', b'z')
271 >>> insertplainheader([b'', b'Date: y'], b'Date', b'z')
272 ['Date: z', '', 'Date: y']
272 ['Date: z', '', 'Date: y']
273 >>> insertplainheader([b'foo: bar', b'DATE: z', b'x'], b'From', b'y')
273 >>> insertplainheader([b'foo: bar', b'DATE: z', b'x'], b'From', b'y')
274 ['From: y', 'foo: bar', 'DATE: z', '', 'x']
274 ['From: y', 'foo: bar', 'DATE: z', '', 'x']
275 """
275 """
276 newprio = PLAINHEADERS[header.lower()]
276 newprio = PLAINHEADERS[header.lower()]
277 bestpos = len(lines)
277 bestpos = len(lines)
278 for i, line in enumerate(lines):
278 for i, line in enumerate(lines):
279 if b':' in line:
279 if b':' in line:
280 lheader = line.split(b':', 1)[0].strip().lower()
280 lheader = line.split(b':', 1)[0].strip().lower()
281 lprio = PLAINHEADERS.get(lheader, newprio + 1)
281 lprio = PLAINHEADERS.get(lheader, newprio + 1)
282 if lprio == newprio:
282 if lprio == newprio:
283 lines[i] = b'%s: %s' % (header, value)
283 lines[i] = b'%s: %s' % (header, value)
284 return lines
284 return lines
285 if lprio > newprio and i < bestpos:
285 if lprio > newprio and i < bestpos:
286 bestpos = i
286 bestpos = i
287 else:
287 else:
288 if line:
288 if line:
289 lines.insert(i, b'')
289 lines.insert(i, b'')
290 if i < bestpos:
290 if i < bestpos:
291 bestpos = i
291 bestpos = i
292 break
292 break
293 lines.insert(bestpos, b'%s: %s' % (header, value))
293 lines.insert(bestpos, b'%s: %s' % (header, value))
294 return lines
294 return lines
295
295
296
296
297 class patchheader(object):
297 class patchheader(object):
298 def __init__(self, pf, plainmode=False):
298 def __init__(self, pf, plainmode=False):
299 def eatdiff(lines):
299 def eatdiff(lines):
300 while lines:
300 while lines:
301 l = lines[-1]
301 l = lines[-1]
302 if (
302 if (
303 l.startswith(b"diff -")
303 l.startswith(b"diff -")
304 or l.startswith(b"Index:")
304 or l.startswith(b"Index:")
305 or l.startswith(b"===========")
305 or l.startswith(b"===========")
306 ):
306 ):
307 del lines[-1]
307 del lines[-1]
308 else:
308 else:
309 break
309 break
310
310
311 def eatempty(lines):
311 def eatempty(lines):
312 while lines:
312 while lines:
313 if not lines[-1].strip():
313 if not lines[-1].strip():
314 del lines[-1]
314 del lines[-1]
315 else:
315 else:
316 break
316 break
317
317
318 message = []
318 message = []
319 comments = []
319 comments = []
320 user = None
320 user = None
321 date = None
321 date = None
322 parent = None
322 parent = None
323 format = None
323 format = None
324 subject = None
324 subject = None
325 branch = None
325 branch = None
326 nodeid = None
326 nodeid = None
327 diffstart = 0
327 diffstart = 0
328
328
329 for line in open(pf, b'rb'):
329 for line in open(pf, b'rb'):
330 line = line.rstrip()
330 line = line.rstrip()
331 if line.startswith(b'diff --git') or (
331 if line.startswith(b'diff --git') or (
332 diffstart and line.startswith(b'+++ ')
332 diffstart and line.startswith(b'+++ ')
333 ):
333 ):
334 diffstart = 2
334 diffstart = 2
335 break
335 break
336 diffstart = 0 # reset
336 diffstart = 0 # reset
337 if line.startswith(b"--- "):
337 if line.startswith(b"--- "):
338 diffstart = 1
338 diffstart = 1
339 continue
339 continue
340 elif format == b"hgpatch":
340 elif format == b"hgpatch":
341 # parse values when importing the result of an hg export
341 # parse values when importing the result of an hg export
342 if line.startswith(b"# User "):
342 if line.startswith(b"# User "):
343 user = line[7:]
343 user = line[7:]
344 elif line.startswith(b"# Date "):
344 elif line.startswith(b"# Date "):
345 date = line[7:]
345 date = line[7:]
346 elif line.startswith(b"# Parent "):
346 elif line.startswith(b"# Parent "):
347 parent = line[9:].lstrip() # handle double trailing space
347 parent = line[9:].lstrip() # handle double trailing space
348 elif line.startswith(b"# Branch "):
348 elif line.startswith(b"# Branch "):
349 branch = line[9:]
349 branch = line[9:]
350 elif line.startswith(b"# Node ID "):
350 elif line.startswith(b"# Node ID "):
351 nodeid = line[10:]
351 nodeid = line[10:]
352 elif not line.startswith(b"# ") and line:
352 elif not line.startswith(b"# ") and line:
353 message.append(line)
353 message.append(line)
354 format = None
354 format = None
355 elif line == b'# HG changeset patch':
355 elif line == b'# HG changeset patch':
356 message = []
356 message = []
357 format = b"hgpatch"
357 format = b"hgpatch"
358 elif format != b"tagdone" and (
358 elif format != b"tagdone" and (
359 line.startswith(b"Subject: ") or line.startswith(b"subject: ")
359 line.startswith(b"Subject: ") or line.startswith(b"subject: ")
360 ):
360 ):
361 subject = line[9:]
361 subject = line[9:]
362 format = b"tag"
362 format = b"tag"
363 elif format != b"tagdone" and (
363 elif format != b"tagdone" and (
364 line.startswith(b"From: ") or line.startswith(b"from: ")
364 line.startswith(b"From: ") or line.startswith(b"from: ")
365 ):
365 ):
366 user = line[6:]
366 user = line[6:]
367 format = b"tag"
367 format = b"tag"
368 elif format != b"tagdone" and (
368 elif format != b"tagdone" and (
369 line.startswith(b"Date: ") or line.startswith(b"date: ")
369 line.startswith(b"Date: ") or line.startswith(b"date: ")
370 ):
370 ):
371 date = line[6:]
371 date = line[6:]
372 format = b"tag"
372 format = b"tag"
373 elif format == b"tag" and line == b"":
373 elif format == b"tag" and line == b"":
374 # when looking for tags (subject: from: etc) they
374 # when looking for tags (subject: from: etc) they
375 # end once you find a blank line in the source
375 # end once you find a blank line in the source
376 format = b"tagdone"
376 format = b"tagdone"
377 elif message or line:
377 elif message or line:
378 message.append(line)
378 message.append(line)
379 comments.append(line)
379 comments.append(line)
380
380
381 eatdiff(message)
381 eatdiff(message)
382 eatdiff(comments)
382 eatdiff(comments)
383 # Remember the exact starting line of the patch diffs before consuming
383 # Remember the exact starting line of the patch diffs before consuming
384 # empty lines, for external use by TortoiseHg and others
384 # empty lines, for external use by TortoiseHg and others
385 self.diffstartline = len(comments)
385 self.diffstartline = len(comments)
386 eatempty(message)
386 eatempty(message)
387 eatempty(comments)
387 eatempty(comments)
388
388
389 # make sure message isn't empty
389 # make sure message isn't empty
390 if format and format.startswith(b"tag") and subject:
390 if format and format.startswith(b"tag") and subject:
391 message.insert(0, subject)
391 message.insert(0, subject)
392
392
393 self.message = message
393 self.message = message
394 self.comments = comments
394 self.comments = comments
395 self.user = user
395 self.user = user
396 self.date = date
396 self.date = date
397 self.parent = parent
397 self.parent = parent
398 # nodeid and branch are for external use by TortoiseHg and others
398 # nodeid and branch are for external use by TortoiseHg and others
399 self.nodeid = nodeid
399 self.nodeid = nodeid
400 self.branch = branch
400 self.branch = branch
401 self.haspatch = diffstart > 1
401 self.haspatch = diffstart > 1
402 self.plainmode = (
402 self.plainmode = (
403 plainmode
403 plainmode
404 or b'# HG changeset patch' not in self.comments
404 or b'# HG changeset patch' not in self.comments
405 and any(
405 and any(
406 c.startswith(b'Date: ') or c.startswith(b'From: ')
406 c.startswith(b'Date: ') or c.startswith(b'From: ')
407 for c in self.comments
407 for c in self.comments
408 )
408 )
409 )
409 )
410
410
411 def setuser(self, user):
411 def setuser(self, user):
412 try:
412 try:
413 inserthgheader(self.comments, b'# User ', user)
413 inserthgheader(self.comments, b'# User ', user)
414 except ValueError:
414 except ValueError:
415 if self.plainmode:
415 if self.plainmode:
416 insertplainheader(self.comments, b'From', user)
416 insertplainheader(self.comments, b'From', user)
417 else:
417 else:
418 tmp = [b'# HG changeset patch', b'# User ' + user]
418 tmp = [b'# HG changeset patch', b'# User ' + user]
419 self.comments = tmp + self.comments
419 self.comments = tmp + self.comments
420 self.user = user
420 self.user = user
421
421
422 def setdate(self, date):
422 def setdate(self, date):
423 try:
423 try:
424 inserthgheader(self.comments, b'# Date ', date)
424 inserthgheader(self.comments, b'# Date ', date)
425 except ValueError:
425 except ValueError:
426 if self.plainmode:
426 if self.plainmode:
427 insertplainheader(self.comments, b'Date', date)
427 insertplainheader(self.comments, b'Date', date)
428 else:
428 else:
429 tmp = [b'# HG changeset patch', b'# Date ' + date]
429 tmp = [b'# HG changeset patch', b'# Date ' + date]
430 self.comments = tmp + self.comments
430 self.comments = tmp + self.comments
431 self.date = date
431 self.date = date
432
432
433 def setparent(self, parent):
433 def setparent(self, parent):
434 try:
434 try:
435 inserthgheader(self.comments, b'# Parent ', parent)
435 inserthgheader(self.comments, b'# Parent ', parent)
436 except ValueError:
436 except ValueError:
437 if not self.plainmode:
437 if not self.plainmode:
438 tmp = [b'# HG changeset patch', b'# Parent ' + parent]
438 tmp = [b'# HG changeset patch', b'# Parent ' + parent]
439 self.comments = tmp + self.comments
439 self.comments = tmp + self.comments
440 self.parent = parent
440 self.parent = parent
441
441
442 def setmessage(self, message):
442 def setmessage(self, message):
443 if self.comments:
443 if self.comments:
444 self._delmsg()
444 self._delmsg()
445 self.message = [message]
445 self.message = [message]
446 if message:
446 if message:
447 if self.plainmode and self.comments and self.comments[-1]:
447 if self.plainmode and self.comments and self.comments[-1]:
448 self.comments.append(b'')
448 self.comments.append(b'')
449 self.comments.append(message)
449 self.comments.append(message)
450
450
451 def __bytes__(self):
451 def __bytes__(self):
452 s = b'\n'.join(self.comments).rstrip()
452 s = b'\n'.join(self.comments).rstrip()
453 if not s:
453 if not s:
454 return b''
454 return b''
455 return s + b'\n\n'
455 return s + b'\n\n'
456
456
457 __str__ = encoding.strmethod(__bytes__)
457 __str__ = encoding.strmethod(__bytes__)
458
458
459 def _delmsg(self):
459 def _delmsg(self):
460 """Remove existing message, keeping the rest of the comments fields.
460 """Remove existing message, keeping the rest of the comments fields.
461 If comments contains 'subject: ', message will prepend
461 If comments contains 'subject: ', message will prepend
462 the field and a blank line."""
462 the field and a blank line."""
463 if self.message:
463 if self.message:
464 subj = b'subject: ' + self.message[0].lower()
464 subj = b'subject: ' + self.message[0].lower()
465 for i in pycompat.xrange(len(self.comments)):
465 for i in pycompat.xrange(len(self.comments)):
466 if subj == self.comments[i].lower():
466 if subj == self.comments[i].lower():
467 del self.comments[i]
467 del self.comments[i]
468 self.message = self.message[2:]
468 self.message = self.message[2:]
469 break
469 break
470 ci = 0
470 ci = 0
471 for mi in self.message:
471 for mi in self.message:
472 while mi != self.comments[ci]:
472 while mi != self.comments[ci]:
473 ci += 1
473 ci += 1
474 del self.comments[ci]
474 del self.comments[ci]
475
475
476
476
477 def newcommit(repo, phase, *args, **kwargs):
477 def newcommit(repo, phase, *args, **kwargs):
478 """helper dedicated to ensure a commit respect mq.secret setting
478 """helper dedicated to ensure a commit respect mq.secret setting
479
479
480 It should be used instead of repo.commit inside the mq source for operation
480 It should be used instead of repo.commit inside the mq source for operation
481 creating new changeset.
481 creating new changeset.
482 """
482 """
483 repo = repo.unfiltered()
483 repo = repo.unfiltered()
484 if phase is None:
484 if phase is None:
485 if repo.ui.configbool(b'mq', b'secret'):
485 if repo.ui.configbool(b'mq', b'secret'):
486 phase = phases.secret
486 phase = phases.secret
487 overrides = {(b'ui', b'allowemptycommit'): True}
487 overrides = {(b'ui', b'allowemptycommit'): True}
488 if phase is not None:
488 if phase is not None:
489 overrides[(b'phases', b'new-commit')] = phase
489 overrides[(b'phases', b'new-commit')] = phase
490 with repo.ui.configoverride(overrides, b'mq'):
490 with repo.ui.configoverride(overrides, b'mq'):
491 repo.ui.setconfig(b'ui', b'allowemptycommit', True)
491 repo.ui.setconfig(b'ui', b'allowemptycommit', True)
492 return repo.commit(*args, **kwargs)
492 return repo.commit(*args, **kwargs)
493
493
494
494
495 class AbortNoCleanup(error.Abort):
495 class AbortNoCleanup(error.Abort):
496 pass
496 pass
497
497
498
498
499 class queue(object):
499 class queue(object):
500 def __init__(self, ui, baseui, path, patchdir=None):
500 def __init__(self, ui, baseui, path, patchdir=None):
501 self.basepath = path
501 self.basepath = path
502 try:
502 try:
503 with open(os.path.join(path, b'patches.queue'), 'rb') as fh:
503 with open(os.path.join(path, b'patches.queue'), 'rb') as fh:
504 cur = fh.read().rstrip()
504 cur = fh.read().rstrip()
505
505
506 if not cur:
506 if not cur:
507 curpath = os.path.join(path, b'patches')
507 curpath = os.path.join(path, b'patches')
508 else:
508 else:
509 curpath = os.path.join(path, b'patches-' + cur)
509 curpath = os.path.join(path, b'patches-' + cur)
510 except IOError:
510 except IOError:
511 curpath = os.path.join(path, b'patches')
511 curpath = os.path.join(path, b'patches')
512 self.path = patchdir or curpath
512 self.path = patchdir or curpath
513 self.opener = vfsmod.vfs(self.path)
513 self.opener = vfsmod.vfs(self.path)
514 self.ui = ui
514 self.ui = ui
515 self.baseui = baseui
515 self.baseui = baseui
516 self.applieddirty = False
516 self.applieddirty = False
517 self.seriesdirty = False
517 self.seriesdirty = False
518 self.added = []
518 self.added = []
519 self.seriespath = b"series"
519 self.seriespath = b"series"
520 self.statuspath = b"status"
520 self.statuspath = b"status"
521 self.guardspath = b"guards"
521 self.guardspath = b"guards"
522 self.activeguards = None
522 self.activeguards = None
523 self.guardsdirty = False
523 self.guardsdirty = False
524 # Handle mq.git as a bool with extended values
524 # Handle mq.git as a bool with extended values
525 gitmode = ui.config(b'mq', b'git').lower()
525 gitmode = ui.config(b'mq', b'git').lower()
526 boolmode = stringutil.parsebool(gitmode)
526 boolmode = stringutil.parsebool(gitmode)
527 if boolmode is not None:
527 if boolmode is not None:
528 if boolmode:
528 if boolmode:
529 gitmode = b'yes'
529 gitmode = b'yes'
530 else:
530 else:
531 gitmode = b'no'
531 gitmode = b'no'
532 self.gitmode = gitmode
532 self.gitmode = gitmode
533 # deprecated config: mq.plain
533 # deprecated config: mq.plain
534 self.plainmode = ui.configbool(b'mq', b'plain')
534 self.plainmode = ui.configbool(b'mq', b'plain')
535 self.checkapplied = True
535 self.checkapplied = True
536
536
537 @util.propertycache
537 @util.propertycache
538 def applied(self):
538 def applied(self):
539 def parselines(lines):
539 def parselines(lines):
540 for l in lines:
540 for l in lines:
541 entry = l.split(b':', 1)
541 entry = l.split(b':', 1)
542 if len(entry) > 1:
542 if len(entry) > 1:
543 n, name = entry
543 n, name = entry
544 yield statusentry(bin(n), name)
544 yield statusentry(bin(n), name)
545 elif l.strip():
545 elif l.strip():
546 self.ui.warn(
546 self.ui.warn(
547 _(b'malformated mq status line: %s\n')
547 _(b'malformated mq status line: %s\n')
548 % stringutil.pprint(entry)
548 % stringutil.pprint(entry)
549 )
549 )
550 # else we ignore empty lines
550 # else we ignore empty lines
551
551
552 try:
552 try:
553 lines = self.opener.read(self.statuspath).splitlines()
553 lines = self.opener.read(self.statuspath).splitlines()
554 return list(parselines(lines))
554 return list(parselines(lines))
555 except IOError as e:
555 except IOError as e:
556 if e.errno == errno.ENOENT:
556 if e.errno == errno.ENOENT:
557 return []
557 return []
558 raise
558 raise
559
559
560 @util.propertycache
560 @util.propertycache
561 def fullseries(self):
561 def fullseries(self):
562 try:
562 try:
563 return self.opener.read(self.seriespath).splitlines()
563 return self.opener.read(self.seriespath).splitlines()
564 except IOError as e:
564 except IOError as e:
565 if e.errno == errno.ENOENT:
565 if e.errno == errno.ENOENT:
566 return []
566 return []
567 raise
567 raise
568
568
569 @util.propertycache
569 @util.propertycache
570 def series(self):
570 def series(self):
571 self.parseseries()
571 self.parseseries()
572 return self.series
572 return self.series
573
573
574 @util.propertycache
574 @util.propertycache
575 def seriesguards(self):
575 def seriesguards(self):
576 self.parseseries()
576 self.parseseries()
577 return self.seriesguards
577 return self.seriesguards
578
578
579 def invalidate(self):
579 def invalidate(self):
580 for a in 'applied fullseries series seriesguards'.split():
580 for a in 'applied fullseries series seriesguards'.split():
581 if a in self.__dict__:
581 if a in self.__dict__:
582 delattr(self, a)
582 delattr(self, a)
583 self.applieddirty = False
583 self.applieddirty = False
584 self.seriesdirty = False
584 self.seriesdirty = False
585 self.guardsdirty = False
585 self.guardsdirty = False
586 self.activeguards = None
586 self.activeguards = None
587
587
588 def diffopts(self, opts=None, patchfn=None, plain=False):
588 def diffopts(self, opts=None, patchfn=None, plain=False):
589 """Return diff options tweaked for this mq use, possibly upgrading to
589 """Return diff options tweaked for this mq use, possibly upgrading to
590 git format, and possibly plain and without lossy options."""
590 git format, and possibly plain and without lossy options."""
591 diffopts = patchmod.difffeatureopts(
591 diffopts = patchmod.difffeatureopts(
592 self.ui,
592 self.ui,
593 opts,
593 opts,
594 git=True,
594 git=True,
595 whitespace=not plain,
595 whitespace=not plain,
596 formatchanging=not plain,
596 formatchanging=not plain,
597 )
597 )
598 if self.gitmode == b'auto':
598 if self.gitmode == b'auto':
599 diffopts.upgrade = True
599 diffopts.upgrade = True
600 elif self.gitmode == b'keep':
600 elif self.gitmode == b'keep':
601 pass
601 pass
602 elif self.gitmode in (b'yes', b'no'):
602 elif self.gitmode in (b'yes', b'no'):
603 diffopts.git = self.gitmode == b'yes'
603 diffopts.git = self.gitmode == b'yes'
604 else:
604 else:
605 raise error.Abort(
605 raise error.Abort(
606 _(b'mq.git option can be auto/keep/yes/no got %s')
606 _(b'mq.git option can be auto/keep/yes/no got %s')
607 % self.gitmode
607 % self.gitmode
608 )
608 )
609 if patchfn:
609 if patchfn:
610 diffopts = self.patchopts(diffopts, patchfn)
610 diffopts = self.patchopts(diffopts, patchfn)
611 return diffopts
611 return diffopts
612
612
613 def patchopts(self, diffopts, *patches):
613 def patchopts(self, diffopts, *patches):
614 """Return a copy of input diff options with git set to true if
614 """Return a copy of input diff options with git set to true if
615 referenced patch is a git patch and should be preserved as such.
615 referenced patch is a git patch and should be preserved as such.
616 """
616 """
617 diffopts = diffopts.copy()
617 diffopts = diffopts.copy()
618 if not diffopts.git and self.gitmode == b'keep':
618 if not diffopts.git and self.gitmode == b'keep':
619 for patchfn in patches:
619 for patchfn in patches:
620 patchf = self.opener(patchfn, b'r')
620 patchf = self.opener(patchfn, b'r')
621 # if the patch was a git patch, refresh it as a git patch
621 # if the patch was a git patch, refresh it as a git patch
622 diffopts.git = any(
622 diffopts.git = any(
623 line.startswith(b'diff --git') for line in patchf
623 line.startswith(b'diff --git') for line in patchf
624 )
624 )
625 patchf.close()
625 patchf.close()
626 return diffopts
626 return diffopts
627
627
628 def join(self, *p):
628 def join(self, *p):
629 return os.path.join(self.path, *p)
629 return os.path.join(self.path, *p)
630
630
631 def findseries(self, patch):
631 def findseries(self, patch):
632 def matchpatch(l):
632 def matchpatch(l):
633 l = l.split(b'#', 1)[0]
633 l = l.split(b'#', 1)[0]
634 return l.strip() == patch
634 return l.strip() == patch
635
635
636 for index, l in enumerate(self.fullseries):
636 for index, l in enumerate(self.fullseries):
637 if matchpatch(l):
637 if matchpatch(l):
638 return index
638 return index
639 return None
639 return None
640
640
641 guard_re = re.compile(br'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
641 guard_re = re.compile(br'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
642
642
643 def parseseries(self):
643 def parseseries(self):
644 self.series = []
644 self.series = []
645 self.seriesguards = []
645 self.seriesguards = []
646 for l in self.fullseries:
646 for l in self.fullseries:
647 h = l.find(b'#')
647 h = l.find(b'#')
648 if h == -1:
648 if h == -1:
649 patch = l
649 patch = l
650 comment = b''
650 comment = b''
651 elif h == 0:
651 elif h == 0:
652 continue
652 continue
653 else:
653 else:
654 patch = l[:h]
654 patch = l[:h]
655 comment = l[h:]
655 comment = l[h:]
656 patch = patch.strip()
656 patch = patch.strip()
657 if patch:
657 if patch:
658 if patch in self.series:
658 if patch in self.series:
659 raise error.Abort(
659 raise error.Abort(
660 _(b'%s appears more than once in %s')
660 _(b'%s appears more than once in %s')
661 % (patch, self.join(self.seriespath))
661 % (patch, self.join(self.seriespath))
662 )
662 )
663 self.series.append(patch)
663 self.series.append(patch)
664 self.seriesguards.append(self.guard_re.findall(comment))
664 self.seriesguards.append(self.guard_re.findall(comment))
665
665
666 def checkguard(self, guard):
666 def checkguard(self, guard):
667 if not guard:
667 if not guard:
668 return _(b'guard cannot be an empty string')
668 return _(b'guard cannot be an empty string')
669 bad_chars = b'# \t\r\n\f'
669 bad_chars = b'# \t\r\n\f'
670 first = guard[0]
670 first = guard[0]
671 if first in b'-+':
671 if first in b'-+':
672 return _(b'guard %r starts with invalid character: %r') % (
672 return _(b'guard %r starts with invalid character: %r') % (
673 guard,
673 guard,
674 first,
674 first,
675 )
675 )
676 for c in bad_chars:
676 for c in bad_chars:
677 if c in guard:
677 if c in guard:
678 return _(b'invalid character in guard %r: %r') % (guard, c)
678 return _(b'invalid character in guard %r: %r') % (guard, c)
679
679
680 def setactive(self, guards):
680 def setactive(self, guards):
681 for guard in guards:
681 for guard in guards:
682 bad = self.checkguard(guard)
682 bad = self.checkguard(guard)
683 if bad:
683 if bad:
684 raise error.Abort(bad)
684 raise error.Abort(bad)
685 guards = sorted(set(guards))
685 guards = sorted(set(guards))
686 self.ui.debug(b'active guards: %s\n' % b' '.join(guards))
686 self.ui.debug(b'active guards: %s\n' % b' '.join(guards))
687 self.activeguards = guards
687 self.activeguards = guards
688 self.guardsdirty = True
688 self.guardsdirty = True
689
689
690 def active(self):
690 def active(self):
691 if self.activeguards is None:
691 if self.activeguards is None:
692 self.activeguards = []
692 self.activeguards = []
693 try:
693 try:
694 guards = self.opener.read(self.guardspath).split()
694 guards = self.opener.read(self.guardspath).split()
695 except IOError as err:
695 except IOError as err:
696 if err.errno != errno.ENOENT:
696 if err.errno != errno.ENOENT:
697 raise
697 raise
698 guards = []
698 guards = []
699 for i, guard in enumerate(guards):
699 for i, guard in enumerate(guards):
700 bad = self.checkguard(guard)
700 bad = self.checkguard(guard)
701 if bad:
701 if bad:
702 self.ui.warn(
702 self.ui.warn(
703 b'%s:%d: %s\n'
703 b'%s:%d: %s\n'
704 % (self.join(self.guardspath), i + 1, bad)
704 % (self.join(self.guardspath), i + 1, bad)
705 )
705 )
706 else:
706 else:
707 self.activeguards.append(guard)
707 self.activeguards.append(guard)
708 return self.activeguards
708 return self.activeguards
709
709
710 def setguards(self, idx, guards):
710 def setguards(self, idx, guards):
711 for g in guards:
711 for g in guards:
712 if len(g) < 2:
712 if len(g) < 2:
713 raise error.Abort(_(b'guard %r too short') % g)
713 raise error.Abort(_(b'guard %r too short') % g)
714 if g[0] not in b'-+':
714 if g[0] not in b'-+':
715 raise error.Abort(_(b'guard %r starts with invalid char') % g)
715 raise error.Abort(_(b'guard %r starts with invalid char') % g)
716 bad = self.checkguard(g[1:])
716 bad = self.checkguard(g[1:])
717 if bad:
717 if bad:
718 raise error.Abort(bad)
718 raise error.Abort(bad)
719 drop = self.guard_re.sub(b'', self.fullseries[idx])
719 drop = self.guard_re.sub(b'', self.fullseries[idx])
720 self.fullseries[idx] = drop + b''.join([b' #' + g for g in guards])
720 self.fullseries[idx] = drop + b''.join([b' #' + g for g in guards])
721 self.parseseries()
721 self.parseseries()
722 self.seriesdirty = True
722 self.seriesdirty = True
723
723
724 def pushable(self, idx):
724 def pushable(self, idx):
725 if isinstance(idx, bytes):
725 if isinstance(idx, bytes):
726 idx = self.series.index(idx)
726 idx = self.series.index(idx)
727 patchguards = self.seriesguards[idx]
727 patchguards = self.seriesguards[idx]
728 if not patchguards:
728 if not patchguards:
729 return True, None
729 return True, None
730 guards = self.active()
730 guards = self.active()
731 exactneg = [
731 exactneg = [
732 g for g in patchguards if g.startswith(b'-') and g[1:] in guards
732 g for g in patchguards if g.startswith(b'-') and g[1:] in guards
733 ]
733 ]
734 if exactneg:
734 if exactneg:
735 return False, stringutil.pprint(exactneg[0])
735 return False, stringutil.pprint(exactneg[0])
736 pos = [g for g in patchguards if g.startswith(b'+')]
736 pos = [g for g in patchguards if g.startswith(b'+')]
737 exactpos = [g for g in pos if g[1:] in guards]
737 exactpos = [g for g in pos if g[1:] in guards]
738 if pos:
738 if pos:
739 if exactpos:
739 if exactpos:
740 return True, stringutil.pprint(exactpos[0])
740 return True, stringutil.pprint(exactpos[0])
741 return False, b' '.join([stringutil.pprint(p) for p in pos])
741 return False, b' '.join([stringutil.pprint(p) for p in pos])
742 return True, b''
742 return True, b''
743
743
744 def explainpushable(self, idx, all_patches=False):
744 def explainpushable(self, idx, all_patches=False):
745 if all_patches:
745 if all_patches:
746 write = self.ui.write
746 write = self.ui.write
747 else:
747 else:
748 write = self.ui.warn
748 write = self.ui.warn
749
749
750 if all_patches or self.ui.verbose:
750 if all_patches or self.ui.verbose:
751 if isinstance(idx, bytes):
751 if isinstance(idx, bytes):
752 idx = self.series.index(idx)
752 idx = self.series.index(idx)
753 pushable, why = self.pushable(idx)
753 pushable, why = self.pushable(idx)
754 if all_patches and pushable:
754 if all_patches and pushable:
755 if why is None:
755 if why is None:
756 write(
756 write(
757 _(b'allowing %s - no guards in effect\n')
757 _(b'allowing %s - no guards in effect\n')
758 % self.series[idx]
758 % self.series[idx]
759 )
759 )
760 else:
760 else:
761 if not why:
761 if not why:
762 write(
762 write(
763 _(b'allowing %s - no matching negative guards\n')
763 _(b'allowing %s - no matching negative guards\n')
764 % self.series[idx]
764 % self.series[idx]
765 )
765 )
766 else:
766 else:
767 write(
767 write(
768 _(b'allowing %s - guarded by %s\n')
768 _(b'allowing %s - guarded by %s\n')
769 % (self.series[idx], why)
769 % (self.series[idx], why)
770 )
770 )
771 if not pushable:
771 if not pushable:
772 if why:
772 if why:
773 write(
773 write(
774 _(b'skipping %s - guarded by %s\n')
774 _(b'skipping %s - guarded by %s\n')
775 % (self.series[idx], why)
775 % (self.series[idx], why)
776 )
776 )
777 else:
777 else:
778 write(
778 write(
779 _(b'skipping %s - no matching guards\n')
779 _(b'skipping %s - no matching guards\n')
780 % self.series[idx]
780 % self.series[idx]
781 )
781 )
782
782
783 def savedirty(self):
783 def savedirty(self):
784 def writelist(items, path):
784 def writelist(items, path):
785 fp = self.opener(path, b'wb')
785 fp = self.opener(path, b'wb')
786 for i in items:
786 for i in items:
787 fp.write(b"%s\n" % i)
787 fp.write(b"%s\n" % i)
788 fp.close()
788 fp.close()
789
789
790 if self.applieddirty:
790 if self.applieddirty:
791 writelist(map(bytes, self.applied), self.statuspath)
791 writelist(map(bytes, self.applied), self.statuspath)
792 self.applieddirty = False
792 self.applieddirty = False
793 if self.seriesdirty:
793 if self.seriesdirty:
794 writelist(self.fullseries, self.seriespath)
794 writelist(self.fullseries, self.seriespath)
795 self.seriesdirty = False
795 self.seriesdirty = False
796 if self.guardsdirty:
796 if self.guardsdirty:
797 writelist(self.activeguards, self.guardspath)
797 writelist(self.activeguards, self.guardspath)
798 self.guardsdirty = False
798 self.guardsdirty = False
799 if self.added:
799 if self.added:
800 qrepo = self.qrepo()
800 qrepo = self.qrepo()
801 if qrepo:
801 if qrepo:
802 qrepo[None].add(f for f in self.added if f not in qrepo[None])
802 qrepo[None].add(f for f in self.added if f not in qrepo[None])
803 self.added = []
803 self.added = []
804
804
805 def removeundo(self, repo):
805 def removeundo(self, repo):
806 undo = repo.sjoin(b'undo')
806 undo = repo.sjoin(b'undo')
807 if not os.path.exists(undo):
807 if not os.path.exists(undo):
808 return
808 return
809 try:
809 try:
810 os.unlink(undo)
810 os.unlink(undo)
811 except OSError as inst:
811 except OSError as inst:
812 self.ui.warn(
812 self.ui.warn(
813 _(b'error removing undo: %s\n') % stringutil.forcebytestr(inst)
813 _(b'error removing undo: %s\n') % stringutil.forcebytestr(inst)
814 )
814 )
815
815
816 def backup(self, repo, files, copy=False):
816 def backup(self, repo, files, copy=False):
817 # backup local changes in --force case
817 # backup local changes in --force case
818 for f in sorted(files):
818 for f in sorted(files):
819 absf = repo.wjoin(f)
819 absf = repo.wjoin(f)
820 if os.path.lexists(absf):
820 if os.path.lexists(absf):
821 absorig = scmutil.backuppath(self.ui, repo, f)
821 absorig = scmutil.backuppath(self.ui, repo, f)
822 self.ui.note(
822 self.ui.note(
823 _(b'saving current version of %s as %s\n')
823 _(b'saving current version of %s as %s\n')
824 % (f, os.path.relpath(absorig))
824 % (f, os.path.relpath(absorig))
825 )
825 )
826
826
827 if copy:
827 if copy:
828 util.copyfile(absf, absorig)
828 util.copyfile(absf, absorig)
829 else:
829 else:
830 util.rename(absf, absorig)
830 util.rename(absf, absorig)
831
831
832 def printdiff(
832 def printdiff(
833 self,
833 self,
834 repo,
834 repo,
835 diffopts,
835 diffopts,
836 node1,
836 node1,
837 node2=None,
837 node2=None,
838 files=None,
838 files=None,
839 fp=None,
839 fp=None,
840 changes=None,
840 changes=None,
841 opts=None,
841 opts=None,
842 ):
842 ):
843 if opts is None:
843 if opts is None:
844 opts = {}
844 opts = {}
845 stat = opts.get(b'stat')
845 stat = opts.get(b'stat')
846 m = scmutil.match(repo[node1], files, opts)
846 m = scmutil.match(repo[node1], files, opts)
847 logcmdutil.diffordiffstat(
847 logcmdutil.diffordiffstat(
848 self.ui,
848 self.ui,
849 repo,
849 repo,
850 diffopts,
850 diffopts,
851 repo[node1],
851 repo[node1],
852 repo[node2],
852 repo[node2],
853 m,
853 m,
854 changes,
854 changes,
855 stat,
855 stat,
856 fp,
856 fp,
857 )
857 )
858
858
859 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
859 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
860 # first try just applying the patch
860 # first try just applying the patch
861 (err, n) = self.apply(
861 (err, n) = self.apply(
862 repo, [patch], update_status=False, strict=True, merge=rev
862 repo, [patch], update_status=False, strict=True, merge=rev
863 )
863 )
864
864
865 if err == 0:
865 if err == 0:
866 return (err, n)
866 return (err, n)
867
867
868 if n is None:
868 if n is None:
869 raise error.Abort(_(b"apply failed for patch %s") % patch)
869 raise error.Abort(_(b"apply failed for patch %s") % patch)
870
870
871 self.ui.warn(_(b"patch didn't work out, merging %s\n") % patch)
871 self.ui.warn(_(b"patch didn't work out, merging %s\n") % patch)
872
872
873 # apply failed, strip away that rev and merge.
873 # apply failed, strip away that rev and merge.
874 hg.clean(repo, head)
874 hg.clean(repo, head)
875 strip(self.ui, repo, [n], update=False, backup=False)
875 strip(self.ui, repo, [n], update=False, backup=False)
876
876
877 ctx = repo[rev]
877 ctx = repo[rev]
878 ret = hg.merge(ctx, remind=False)
878 ret = hg.merge(ctx, remind=False)
879 if ret:
879 if ret:
880 raise error.Abort(_(b"update returned %d") % ret)
880 raise error.Abort(_(b"update returned %d") % ret)
881 n = newcommit(repo, None, ctx.description(), ctx.user(), force=True)
881 n = newcommit(repo, None, ctx.description(), ctx.user(), force=True)
882 if n is None:
882 if n is None:
883 raise error.Abort(_(b"repo commit failed"))
883 raise error.Abort(_(b"repo commit failed"))
884 try:
884 try:
885 ph = patchheader(mergeq.join(patch), self.plainmode)
885 ph = patchheader(mergeq.join(patch), self.plainmode)
886 except Exception:
886 except Exception:
887 raise error.Abort(_(b"unable to read %s") % patch)
887 raise error.Abort(_(b"unable to read %s") % patch)
888
888
889 diffopts = self.patchopts(diffopts, patch)
889 diffopts = self.patchopts(diffopts, patch)
890 patchf = self.opener(patch, b"w")
890 patchf = self.opener(patch, b"w")
891 comments = bytes(ph)
891 comments = bytes(ph)
892 if comments:
892 if comments:
893 patchf.write(comments)
893 patchf.write(comments)
894 self.printdiff(repo, diffopts, head, n, fp=patchf)
894 self.printdiff(repo, diffopts, head, n, fp=patchf)
895 patchf.close()
895 patchf.close()
896 self.removeundo(repo)
896 self.removeundo(repo)
897 return (0, n)
897 return (0, n)
898
898
899 def qparents(self, repo, rev=None):
899 def qparents(self, repo, rev=None):
900 """return the mq handled parent or p1
900 """return the mq handled parent or p1
901
901
902 In some case where mq get himself in being the parent of a merge the
902 In some case where mq get himself in being the parent of a merge the
903 appropriate parent may be p2.
903 appropriate parent may be p2.
904 (eg: an in progress merge started with mq disabled)
904 (eg: an in progress merge started with mq disabled)
905
905
906 If no parent are managed by mq, p1 is returned.
906 If no parent are managed by mq, p1 is returned.
907 """
907 """
908 if rev is None:
908 if rev is None:
909 (p1, p2) = repo.dirstate.parents()
909 (p1, p2) = repo.dirstate.parents()
910 if p2 == repo.nullid:
910 if p2 == repo.nullid:
911 return p1
911 return p1
912 if not self.applied:
912 if not self.applied:
913 return None
913 return None
914 return self.applied[-1].node
914 return self.applied[-1].node
915 p1, p2 = repo.changelog.parents(rev)
915 p1, p2 = repo.changelog.parents(rev)
916 if p2 != repo.nullid and p2 in [x.node for x in self.applied]:
916 if p2 != repo.nullid and p2 in [x.node for x in self.applied]:
917 return p2
917 return p2
918 return p1
918 return p1
919
919
920 def mergepatch(self, repo, mergeq, series, diffopts):
920 def mergepatch(self, repo, mergeq, series, diffopts):
921 if not self.applied:
921 if not self.applied:
922 # each of the patches merged in will have two parents. This
922 # each of the patches merged in will have two parents. This
923 # can confuse the qrefresh, qdiff, and strip code because it
923 # can confuse the qrefresh, qdiff, and strip code because it
924 # needs to know which parent is actually in the patch queue.
924 # needs to know which parent is actually in the patch queue.
925 # so, we insert a merge marker with only one parent. This way
925 # so, we insert a merge marker with only one parent. This way
926 # the first patch in the queue is never a merge patch
926 # the first patch in the queue is never a merge patch
927 #
927 #
928 pname = b".hg.patches.merge.marker"
928 pname = b".hg.patches.merge.marker"
929 n = newcommit(repo, None, b'[mq]: merge marker', force=True)
929 n = newcommit(repo, None, b'[mq]: merge marker', force=True)
930 self.removeundo(repo)
930 self.removeundo(repo)
931 self.applied.append(statusentry(n, pname))
931 self.applied.append(statusentry(n, pname))
932 self.applieddirty = True
932 self.applieddirty = True
933
933
934 head = self.qparents(repo)
934 head = self.qparents(repo)
935
935
936 for patch in series:
936 for patch in series:
937 patch = mergeq.lookup(patch, strict=True)
937 patch = mergeq.lookup(patch, strict=True)
938 if not patch:
938 if not patch:
939 self.ui.warn(_(b"patch %s does not exist\n") % patch)
939 self.ui.warn(_(b"patch %s does not exist\n") % patch)
940 return (1, None)
940 return (1, None)
941 pushable, reason = self.pushable(patch)
941 pushable, reason = self.pushable(patch)
942 if not pushable:
942 if not pushable:
943 self.explainpushable(patch, all_patches=True)
943 self.explainpushable(patch, all_patches=True)
944 continue
944 continue
945 info = mergeq.isapplied(patch)
945 info = mergeq.isapplied(patch)
946 if not info:
946 if not info:
947 self.ui.warn(_(b"patch %s is not applied\n") % patch)
947 self.ui.warn(_(b"patch %s is not applied\n") % patch)
948 return (1, None)
948 return (1, None)
949 rev = info[1]
949 rev = info[1]
950 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
950 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
951 if head:
951 if head:
952 self.applied.append(statusentry(head, patch))
952 self.applied.append(statusentry(head, patch))
953 self.applieddirty = True
953 self.applieddirty = True
954 if err:
954 if err:
955 return (err, head)
955 return (err, head)
956 self.savedirty()
956 self.savedirty()
957 return (0, head)
957 return (0, head)
958
958
959 def patch(self, repo, patchfile):
959 def patch(self, repo, patchfile):
960 """Apply patchfile to the working directory.
960 """Apply patchfile to the working directory.
961 patchfile: name of patch file"""
961 patchfile: name of patch file"""
962 files = set()
962 files = set()
963 try:
963 try:
964 fuzz = patchmod.patch(
964 fuzz = patchmod.patch(
965 self.ui, repo, patchfile, strip=1, files=files, eolmode=None
965 self.ui, repo, patchfile, strip=1, files=files, eolmode=None
966 )
966 )
967 return (True, list(files), fuzz)
967 return (True, list(files), fuzz)
968 except Exception as inst:
968 except Exception as inst:
969 self.ui.note(stringutil.forcebytestr(inst) + b'\n')
969 self.ui.note(stringutil.forcebytestr(inst) + b'\n')
970 if not self.ui.verbose:
970 if not self.ui.verbose:
971 self.ui.warn(_(b"patch failed, unable to continue (try -v)\n"))
971 self.ui.warn(_(b"patch failed, unable to continue (try -v)\n"))
972 self.ui.traceback()
972 self.ui.traceback()
973 return (False, list(files), False)
973 return (False, list(files), False)
974
974
975 def apply(
975 def apply(
976 self,
976 self,
977 repo,
977 repo,
978 series,
978 series,
979 list=False,
979 list=False,
980 update_status=True,
980 update_status=True,
981 strict=False,
981 strict=False,
982 patchdir=None,
982 patchdir=None,
983 merge=None,
983 merge=None,
984 all_files=None,
984 all_files=None,
985 tobackup=None,
985 tobackup=None,
986 keepchanges=False,
986 keepchanges=False,
987 ):
987 ):
988 wlock = lock = tr = None
988 wlock = lock = tr = None
989 try:
989 try:
990 wlock = repo.wlock()
990 wlock = repo.wlock()
991 lock = repo.lock()
991 lock = repo.lock()
992 tr = repo.transaction(b"qpush")
992 tr = repo.transaction(b"qpush")
993 try:
993 try:
994 ret = self._apply(
994 ret = self._apply(
995 repo,
995 repo,
996 series,
996 series,
997 list,
997 list,
998 update_status,
998 update_status,
999 strict,
999 strict,
1000 patchdir,
1000 patchdir,
1001 merge,
1001 merge,
1002 all_files=all_files,
1002 all_files=all_files,
1003 tobackup=tobackup,
1003 tobackup=tobackup,
1004 keepchanges=keepchanges,
1004 keepchanges=keepchanges,
1005 )
1005 )
1006 tr.close()
1006 tr.close()
1007 self.savedirty()
1007 self.savedirty()
1008 return ret
1008 return ret
1009 except AbortNoCleanup:
1009 except AbortNoCleanup:
1010 tr.close()
1010 tr.close()
1011 self.savedirty()
1011 self.savedirty()
1012 raise
1012 raise
1013 except: # re-raises
1013 except: # re-raises
1014 try:
1014 try:
1015 tr.abort()
1015 tr.abort()
1016 finally:
1016 finally:
1017 self.invalidate()
1017 self.invalidate()
1018 raise
1018 raise
1019 finally:
1019 finally:
1020 release(tr, lock, wlock)
1020 release(tr, lock, wlock)
1021 self.removeundo(repo)
1021 self.removeundo(repo)
1022
1022
1023 def _apply(
1023 def _apply(
1024 self,
1024 self,
1025 repo,
1025 repo,
1026 series,
1026 series,
1027 list=False,
1027 list=False,
1028 update_status=True,
1028 update_status=True,
1029 strict=False,
1029 strict=False,
1030 patchdir=None,
1030 patchdir=None,
1031 merge=None,
1031 merge=None,
1032 all_files=None,
1032 all_files=None,
1033 tobackup=None,
1033 tobackup=None,
1034 keepchanges=False,
1034 keepchanges=False,
1035 ):
1035 ):
1036 """returns (error, hash)
1036 """returns (error, hash)
1037
1037
1038 error = 1 for unable to read, 2 for patch failed, 3 for patch
1038 error = 1 for unable to read, 2 for patch failed, 3 for patch
1039 fuzz. tobackup is None or a set of files to backup before they
1039 fuzz. tobackup is None or a set of files to backup before they
1040 are modified by a patch.
1040 are modified by a patch.
1041 """
1041 """
1042 # TODO unify with commands.py
1042 # TODO unify with commands.py
1043 if not patchdir:
1043 if not patchdir:
1044 patchdir = self.path
1044 patchdir = self.path
1045 err = 0
1045 err = 0
1046 n = None
1046 n = None
1047 for patchname in series:
1047 for patchname in series:
1048 pushable, reason = self.pushable(patchname)
1048 pushable, reason = self.pushable(patchname)
1049 if not pushable:
1049 if not pushable:
1050 self.explainpushable(patchname, all_patches=True)
1050 self.explainpushable(patchname, all_patches=True)
1051 continue
1051 continue
1052 self.ui.status(_(b"applying %s\n") % patchname)
1052 self.ui.status(_(b"applying %s\n") % patchname)
1053 pf = os.path.join(patchdir, patchname)
1053 pf = os.path.join(patchdir, patchname)
1054
1054
1055 try:
1055 try:
1056 ph = patchheader(self.join(patchname), self.plainmode)
1056 ph = patchheader(self.join(patchname), self.plainmode)
1057 except IOError:
1057 except IOError:
1058 self.ui.warn(_(b"unable to read %s\n") % patchname)
1058 self.ui.warn(_(b"unable to read %s\n") % patchname)
1059 err = 1
1059 err = 1
1060 break
1060 break
1061
1061
1062 message = ph.message
1062 message = ph.message
1063 if not message:
1063 if not message:
1064 # The commit message should not be translated
1064 # The commit message should not be translated
1065 message = b"imported patch %s\n" % patchname
1065 message = b"imported patch %s\n" % patchname
1066 else:
1066 else:
1067 if list:
1067 if list:
1068 # The commit message should not be translated
1068 # The commit message should not be translated
1069 message.append(b"\nimported patch %s" % patchname)
1069 message.append(b"\nimported patch %s" % patchname)
1070 message = b'\n'.join(message)
1070 message = b'\n'.join(message)
1071
1071
1072 if ph.haspatch:
1072 if ph.haspatch:
1073 if tobackup:
1073 if tobackup:
1074 touched = patchmod.changedfiles(self.ui, repo, pf)
1074 touched = patchmod.changedfiles(self.ui, repo, pf)
1075 touched = set(touched) & tobackup
1075 touched = set(touched) & tobackup
1076 if touched and keepchanges:
1076 if touched and keepchanges:
1077 raise AbortNoCleanup(
1077 raise AbortNoCleanup(
1078 _(b"conflicting local changes found"),
1078 _(b"conflicting local changes found"),
1079 hint=_(b"did you forget to qrefresh?"),
1079 hint=_(b"did you forget to qrefresh?"),
1080 )
1080 )
1081 self.backup(repo, touched, copy=True)
1081 self.backup(repo, touched, copy=True)
1082 tobackup = tobackup - touched
1082 tobackup = tobackup - touched
1083 (patcherr, files, fuzz) = self.patch(repo, pf)
1083 (patcherr, files, fuzz) = self.patch(repo, pf)
1084 if all_files is not None:
1084 if all_files is not None:
1085 all_files.update(files)
1085 all_files.update(files)
1086 patcherr = not patcherr
1086 patcherr = not patcherr
1087 else:
1087 else:
1088 self.ui.warn(_(b"patch %s is empty\n") % patchname)
1088 self.ui.warn(_(b"patch %s is empty\n") % patchname)
1089 patcherr, files, fuzz = 0, [], 0
1089 patcherr, files, fuzz = 0, [], 0
1090
1090
1091 if merge and files:
1091 if merge and files:
1092 # Mark as removed/merged and update dirstate parent info
1092 # Mark as removed/merged and update dirstate parent info
1093 removed = []
1094 merged = []
1095 for f in files:
1096 if os.path.lexists(repo.wjoin(f)):
1097 merged.append(f)
1098 else:
1099 removed.append(f)
1100 with repo.dirstate.parentchange():
1093 with repo.dirstate.parentchange():
1101 for f in removed:
1094 for f in files:
1102 repo.dirstate.update_file_p1(f, p1_tracked=True)
1095 repo.dirstate.update_file_p1(f, p1_tracked=True)
1103 for f in merged:
1104 repo.dirstate.merge(f)
1105 p1 = repo.dirstate.p1()
1096 p1 = repo.dirstate.p1()
1106 repo.setparents(p1, merge)
1097 repo.setparents(p1, merge)
1107
1098
1108 if all_files and b'.hgsubstate' in all_files:
1099 if all_files and b'.hgsubstate' in all_files:
1109 wctx = repo[None]
1100 wctx = repo[None]
1110 pctx = repo[b'.']
1101 pctx = repo[b'.']
1111 overwrite = False
1102 overwrite = False
1112 mergedsubstate = subrepoutil.submerge(
1103 mergedsubstate = subrepoutil.submerge(
1113 repo, pctx, wctx, wctx, overwrite
1104 repo, pctx, wctx, wctx, overwrite
1114 )
1105 )
1115 files += mergedsubstate.keys()
1106 files += mergedsubstate.keys()
1116
1107
1117 match = scmutil.matchfiles(repo, files or [])
1108 match = scmutil.matchfiles(repo, files or [])
1118 oldtip = repo.changelog.tip()
1109 oldtip = repo.changelog.tip()
1119 n = newcommit(
1110 n = newcommit(
1120 repo, None, message, ph.user, ph.date, match=match, force=True
1111 repo, None, message, ph.user, ph.date, match=match, force=True
1121 )
1112 )
1122 if repo.changelog.tip() == oldtip:
1113 if repo.changelog.tip() == oldtip:
1123 raise error.Abort(
1114 raise error.Abort(
1124 _(b"qpush exactly duplicates child changeset")
1115 _(b"qpush exactly duplicates child changeset")
1125 )
1116 )
1126 if n is None:
1117 if n is None:
1127 raise error.Abort(_(b"repository commit failed"))
1118 raise error.Abort(_(b"repository commit failed"))
1128
1119
1129 if update_status:
1120 if update_status:
1130 self.applied.append(statusentry(n, patchname))
1121 self.applied.append(statusentry(n, patchname))
1131
1122
1132 if patcherr:
1123 if patcherr:
1133 self.ui.warn(
1124 self.ui.warn(
1134 _(b"patch failed, rejects left in working directory\n")
1125 _(b"patch failed, rejects left in working directory\n")
1135 )
1126 )
1136 err = 2
1127 err = 2
1137 break
1128 break
1138
1129
1139 if fuzz and strict:
1130 if fuzz and strict:
1140 self.ui.warn(_(b"fuzz found when applying patch, stopping\n"))
1131 self.ui.warn(_(b"fuzz found when applying patch, stopping\n"))
1141 err = 3
1132 err = 3
1142 break
1133 break
1143 return (err, n)
1134 return (err, n)
1144
1135
1145 def _cleanup(self, patches, numrevs, keep=False):
1136 def _cleanup(self, patches, numrevs, keep=False):
1146 if not keep:
1137 if not keep:
1147 r = self.qrepo()
1138 r = self.qrepo()
1148 if r:
1139 if r:
1149 r[None].forget(patches)
1140 r[None].forget(patches)
1150 for p in patches:
1141 for p in patches:
1151 try:
1142 try:
1152 os.unlink(self.join(p))
1143 os.unlink(self.join(p))
1153 except OSError as inst:
1144 except OSError as inst:
1154 if inst.errno != errno.ENOENT:
1145 if inst.errno != errno.ENOENT:
1155 raise
1146 raise
1156
1147
1157 qfinished = []
1148 qfinished = []
1158 if numrevs:
1149 if numrevs:
1159 qfinished = self.applied[:numrevs]
1150 qfinished = self.applied[:numrevs]
1160 del self.applied[:numrevs]
1151 del self.applied[:numrevs]
1161 self.applieddirty = True
1152 self.applieddirty = True
1162
1153
1163 unknown = []
1154 unknown = []
1164
1155
1165 sortedseries = []
1156 sortedseries = []
1166 for p in patches:
1157 for p in patches:
1167 idx = self.findseries(p)
1158 idx = self.findseries(p)
1168 if idx is None:
1159 if idx is None:
1169 sortedseries.append((-1, p))
1160 sortedseries.append((-1, p))
1170 else:
1161 else:
1171 sortedseries.append((idx, p))
1162 sortedseries.append((idx, p))
1172
1163
1173 sortedseries.sort(reverse=True)
1164 sortedseries.sort(reverse=True)
1174 for (i, p) in sortedseries:
1165 for (i, p) in sortedseries:
1175 if i != -1:
1166 if i != -1:
1176 del self.fullseries[i]
1167 del self.fullseries[i]
1177 else:
1168 else:
1178 unknown.append(p)
1169 unknown.append(p)
1179
1170
1180 if unknown:
1171 if unknown:
1181 if numrevs:
1172 if numrevs:
1182 rev = {entry.name: entry.node for entry in qfinished}
1173 rev = {entry.name: entry.node for entry in qfinished}
1183 for p in unknown:
1174 for p in unknown:
1184 msg = _(b'revision %s refers to unknown patches: %s\n')
1175 msg = _(b'revision %s refers to unknown patches: %s\n')
1185 self.ui.warn(msg % (short(rev[p]), p))
1176 self.ui.warn(msg % (short(rev[p]), p))
1186 else:
1177 else:
1187 msg = _(b'unknown patches: %s\n')
1178 msg = _(b'unknown patches: %s\n')
1188 raise error.Abort(b''.join(msg % p for p in unknown))
1179 raise error.Abort(b''.join(msg % p for p in unknown))
1189
1180
1190 self.parseseries()
1181 self.parseseries()
1191 self.seriesdirty = True
1182 self.seriesdirty = True
1192 return [entry.node for entry in qfinished]
1183 return [entry.node for entry in qfinished]
1193
1184
1194 def _revpatches(self, repo, revs):
1185 def _revpatches(self, repo, revs):
1195 firstrev = repo[self.applied[0].node].rev()
1186 firstrev = repo[self.applied[0].node].rev()
1196 patches = []
1187 patches = []
1197 for i, rev in enumerate(revs):
1188 for i, rev in enumerate(revs):
1198
1189
1199 if rev < firstrev:
1190 if rev < firstrev:
1200 raise error.Abort(_(b'revision %d is not managed') % rev)
1191 raise error.Abort(_(b'revision %d is not managed') % rev)
1201
1192
1202 ctx = repo[rev]
1193 ctx = repo[rev]
1203 base = self.applied[i].node
1194 base = self.applied[i].node
1204 if ctx.node() != base:
1195 if ctx.node() != base:
1205 msg = _(b'cannot delete revision %d above applied patches')
1196 msg = _(b'cannot delete revision %d above applied patches')
1206 raise error.Abort(msg % rev)
1197 raise error.Abort(msg % rev)
1207
1198
1208 patch = self.applied[i].name
1199 patch = self.applied[i].name
1209 for fmt in (b'[mq]: %s', b'imported patch %s'):
1200 for fmt in (b'[mq]: %s', b'imported patch %s'):
1210 if ctx.description() == fmt % patch:
1201 if ctx.description() == fmt % patch:
1211 msg = _(b'patch %s finalized without changeset message\n')
1202 msg = _(b'patch %s finalized without changeset message\n')
1212 repo.ui.status(msg % patch)
1203 repo.ui.status(msg % patch)
1213 break
1204 break
1214
1205
1215 patches.append(patch)
1206 patches.append(patch)
1216 return patches
1207 return patches
1217
1208
1218 def finish(self, repo, revs):
1209 def finish(self, repo, revs):
1219 # Manually trigger phase computation to ensure phasedefaults is
1210 # Manually trigger phase computation to ensure phasedefaults is
1220 # executed before we remove the patches.
1211 # executed before we remove the patches.
1221 repo._phasecache
1212 repo._phasecache
1222 patches = self._revpatches(repo, sorted(revs))
1213 patches = self._revpatches(repo, sorted(revs))
1223 qfinished = self._cleanup(patches, len(patches))
1214 qfinished = self._cleanup(patches, len(patches))
1224 if qfinished and repo.ui.configbool(b'mq', b'secret'):
1215 if qfinished and repo.ui.configbool(b'mq', b'secret'):
1225 # only use this logic when the secret option is added
1216 # only use this logic when the secret option is added
1226 oldqbase = repo[qfinished[0]]
1217 oldqbase = repo[qfinished[0]]
1227 tphase = phases.newcommitphase(repo.ui)
1218 tphase = phases.newcommitphase(repo.ui)
1228 if oldqbase.phase() > tphase and oldqbase.p1().phase() <= tphase:
1219 if oldqbase.phase() > tphase and oldqbase.p1().phase() <= tphase:
1229 with repo.transaction(b'qfinish') as tr:
1220 with repo.transaction(b'qfinish') as tr:
1230 phases.advanceboundary(repo, tr, tphase, qfinished)
1221 phases.advanceboundary(repo, tr, tphase, qfinished)
1231
1222
1232 def delete(self, repo, patches, opts):
1223 def delete(self, repo, patches, opts):
1233 if not patches and not opts.get(b'rev'):
1224 if not patches and not opts.get(b'rev'):
1234 raise error.Abort(
1225 raise error.Abort(
1235 _(b'qdelete requires at least one revision or patch name')
1226 _(b'qdelete requires at least one revision or patch name')
1236 )
1227 )
1237
1228
1238 realpatches = []
1229 realpatches = []
1239 for patch in patches:
1230 for patch in patches:
1240 patch = self.lookup(patch, strict=True)
1231 patch = self.lookup(patch, strict=True)
1241 info = self.isapplied(patch)
1232 info = self.isapplied(patch)
1242 if info:
1233 if info:
1243 raise error.Abort(_(b"cannot delete applied patch %s") % patch)
1234 raise error.Abort(_(b"cannot delete applied patch %s") % patch)
1244 if patch not in self.series:
1235 if patch not in self.series:
1245 raise error.Abort(_(b"patch %s not in series file") % patch)
1236 raise error.Abort(_(b"patch %s not in series file") % patch)
1246 if patch not in realpatches:
1237 if patch not in realpatches:
1247 realpatches.append(patch)
1238 realpatches.append(patch)
1248
1239
1249 numrevs = 0
1240 numrevs = 0
1250 if opts.get(b'rev'):
1241 if opts.get(b'rev'):
1251 if not self.applied:
1242 if not self.applied:
1252 raise error.Abort(_(b'no patches applied'))
1243 raise error.Abort(_(b'no patches applied'))
1253 revs = scmutil.revrange(repo, opts.get(b'rev'))
1244 revs = scmutil.revrange(repo, opts.get(b'rev'))
1254 revs.sort()
1245 revs.sort()
1255 revpatches = self._revpatches(repo, revs)
1246 revpatches = self._revpatches(repo, revs)
1256 realpatches += revpatches
1247 realpatches += revpatches
1257 numrevs = len(revpatches)
1248 numrevs = len(revpatches)
1258
1249
1259 self._cleanup(realpatches, numrevs, opts.get(b'keep'))
1250 self._cleanup(realpatches, numrevs, opts.get(b'keep'))
1260
1251
1261 def checktoppatch(self, repo):
1252 def checktoppatch(self, repo):
1262 '''check that working directory is at qtip'''
1253 '''check that working directory is at qtip'''
1263 if self.applied:
1254 if self.applied:
1264 top = self.applied[-1].node
1255 top = self.applied[-1].node
1265 patch = self.applied[-1].name
1256 patch = self.applied[-1].name
1266 if repo.dirstate.p1() != top:
1257 if repo.dirstate.p1() != top:
1267 raise error.Abort(_(b"working directory revision is not qtip"))
1258 raise error.Abort(_(b"working directory revision is not qtip"))
1268 return top, patch
1259 return top, patch
1269 return None, None
1260 return None, None
1270
1261
1271 def putsubstate2changes(self, substatestate, changes):
1262 def putsubstate2changes(self, substatestate, changes):
1272 if isinstance(changes, list):
1263 if isinstance(changes, list):
1273 mar = changes[:3]
1264 mar = changes[:3]
1274 else:
1265 else:
1275 mar = (changes.modified, changes.added, changes.removed)
1266 mar = (changes.modified, changes.added, changes.removed)
1276 if any((b'.hgsubstate' in files for files in mar)):
1267 if any((b'.hgsubstate' in files for files in mar)):
1277 return # already listed up
1268 return # already listed up
1278 # not yet listed up
1269 # not yet listed up
1279 if substatestate in b'a?':
1270 if substatestate in b'a?':
1280 mar[1].append(b'.hgsubstate')
1271 mar[1].append(b'.hgsubstate')
1281 elif substatestate in b'r':
1272 elif substatestate in b'r':
1282 mar[2].append(b'.hgsubstate')
1273 mar[2].append(b'.hgsubstate')
1283 else: # modified
1274 else: # modified
1284 mar[0].append(b'.hgsubstate')
1275 mar[0].append(b'.hgsubstate')
1285
1276
1286 def checklocalchanges(self, repo, force=False, refresh=True):
1277 def checklocalchanges(self, repo, force=False, refresh=True):
1287 excsuffix = b''
1278 excsuffix = b''
1288 if refresh:
1279 if refresh:
1289 excsuffix = b', qrefresh first'
1280 excsuffix = b', qrefresh first'
1290 # plain versions for i18n tool to detect them
1281 # plain versions for i18n tool to detect them
1291 _(b"local changes found, qrefresh first")
1282 _(b"local changes found, qrefresh first")
1292 _(b"local changed subrepos found, qrefresh first")
1283 _(b"local changed subrepos found, qrefresh first")
1293
1284
1294 s = repo.status()
1285 s = repo.status()
1295 if not force:
1286 if not force:
1296 cmdutil.checkunfinished(repo)
1287 cmdutil.checkunfinished(repo)
1297 if s.modified or s.added or s.removed or s.deleted:
1288 if s.modified or s.added or s.removed or s.deleted:
1298 _(b"local changes found") # i18n tool detection
1289 _(b"local changes found") # i18n tool detection
1299 raise error.Abort(_(b"local changes found" + excsuffix))
1290 raise error.Abort(_(b"local changes found" + excsuffix))
1300 if checksubstate(repo):
1291 if checksubstate(repo):
1301 _(b"local changed subrepos found") # i18n tool detection
1292 _(b"local changed subrepos found") # i18n tool detection
1302 raise error.Abort(
1293 raise error.Abort(
1303 _(b"local changed subrepos found" + excsuffix)
1294 _(b"local changed subrepos found" + excsuffix)
1304 )
1295 )
1305 else:
1296 else:
1306 cmdutil.checkunfinished(repo, skipmerge=True)
1297 cmdutil.checkunfinished(repo, skipmerge=True)
1307 return s
1298 return s
1308
1299
1309 _reserved = (b'series', b'status', b'guards', b'.', b'..')
1300 _reserved = (b'series', b'status', b'guards', b'.', b'..')
1310
1301
1311 def checkreservedname(self, name):
1302 def checkreservedname(self, name):
1312 if name in self._reserved:
1303 if name in self._reserved:
1313 raise error.Abort(
1304 raise error.Abort(
1314 _(b'"%s" cannot be used as the name of a patch') % name
1305 _(b'"%s" cannot be used as the name of a patch') % name
1315 )
1306 )
1316 if name != name.strip():
1307 if name != name.strip():
1317 # whitespace is stripped by parseseries()
1308 # whitespace is stripped by parseseries()
1318 raise error.Abort(
1309 raise error.Abort(
1319 _(b'patch name cannot begin or end with whitespace')
1310 _(b'patch name cannot begin or end with whitespace')
1320 )
1311 )
1321 for prefix in (b'.hg', b'.mq'):
1312 for prefix in (b'.hg', b'.mq'):
1322 if name.startswith(prefix):
1313 if name.startswith(prefix):
1323 raise error.Abort(
1314 raise error.Abort(
1324 _(b'patch name cannot begin with "%s"') % prefix
1315 _(b'patch name cannot begin with "%s"') % prefix
1325 )
1316 )
1326 for c in (b'#', b':', b'\r', b'\n'):
1317 for c in (b'#', b':', b'\r', b'\n'):
1327 if c in name:
1318 if c in name:
1328 raise error.Abort(
1319 raise error.Abort(
1329 _(b'%r cannot be used in the name of a patch')
1320 _(b'%r cannot be used in the name of a patch')
1330 % pycompat.bytestr(c)
1321 % pycompat.bytestr(c)
1331 )
1322 )
1332
1323
1333 def checkpatchname(self, name, force=False):
1324 def checkpatchname(self, name, force=False):
1334 self.checkreservedname(name)
1325 self.checkreservedname(name)
1335 if not force and os.path.exists(self.join(name)):
1326 if not force and os.path.exists(self.join(name)):
1336 if os.path.isdir(self.join(name)):
1327 if os.path.isdir(self.join(name)):
1337 raise error.Abort(
1328 raise error.Abort(
1338 _(b'"%s" already exists as a directory') % name
1329 _(b'"%s" already exists as a directory') % name
1339 )
1330 )
1340 else:
1331 else:
1341 raise error.Abort(_(b'patch "%s" already exists') % name)
1332 raise error.Abort(_(b'patch "%s" already exists') % name)
1342
1333
1343 def makepatchname(self, title, fallbackname):
1334 def makepatchname(self, title, fallbackname):
1344 """Return a suitable filename for title, adding a suffix to make
1335 """Return a suitable filename for title, adding a suffix to make
1345 it unique in the existing list"""
1336 it unique in the existing list"""
1346 namebase = re.sub(br'[\s\W_]+', b'_', title.lower()).strip(b'_')
1337 namebase = re.sub(br'[\s\W_]+', b'_', title.lower()).strip(b'_')
1347 namebase = namebase[:75] # avoid too long name (issue5117)
1338 namebase = namebase[:75] # avoid too long name (issue5117)
1348 if namebase:
1339 if namebase:
1349 try:
1340 try:
1350 self.checkreservedname(namebase)
1341 self.checkreservedname(namebase)
1351 except error.Abort:
1342 except error.Abort:
1352 namebase = fallbackname
1343 namebase = fallbackname
1353 else:
1344 else:
1354 namebase = fallbackname
1345 namebase = fallbackname
1355 name = namebase
1346 name = namebase
1356 i = 0
1347 i = 0
1357 while True:
1348 while True:
1358 if name not in self.fullseries:
1349 if name not in self.fullseries:
1359 try:
1350 try:
1360 self.checkpatchname(name)
1351 self.checkpatchname(name)
1361 break
1352 break
1362 except error.Abort:
1353 except error.Abort:
1363 pass
1354 pass
1364 i += 1
1355 i += 1
1365 name = b'%s__%d' % (namebase, i)
1356 name = b'%s__%d' % (namebase, i)
1366 return name
1357 return name
1367
1358
1368 def checkkeepchanges(self, keepchanges, force):
1359 def checkkeepchanges(self, keepchanges, force):
1369 if force and keepchanges:
1360 if force and keepchanges:
1370 raise error.Abort(_(b'cannot use both --force and --keep-changes'))
1361 raise error.Abort(_(b'cannot use both --force and --keep-changes'))
1371
1362
1372 def new(self, repo, patchfn, *pats, **opts):
1363 def new(self, repo, patchfn, *pats, **opts):
1373 """options:
1364 """options:
1374 msg: a string or a no-argument function returning a string
1365 msg: a string or a no-argument function returning a string
1375 """
1366 """
1376 opts = pycompat.byteskwargs(opts)
1367 opts = pycompat.byteskwargs(opts)
1377 msg = opts.get(b'msg')
1368 msg = opts.get(b'msg')
1378 edit = opts.get(b'edit')
1369 edit = opts.get(b'edit')
1379 editform = opts.get(b'editform', b'mq.qnew')
1370 editform = opts.get(b'editform', b'mq.qnew')
1380 user = opts.get(b'user')
1371 user = opts.get(b'user')
1381 date = opts.get(b'date')
1372 date = opts.get(b'date')
1382 if date:
1373 if date:
1383 date = dateutil.parsedate(date)
1374 date = dateutil.parsedate(date)
1384 diffopts = self.diffopts({b'git': opts.get(b'git')}, plain=True)
1375 diffopts = self.diffopts({b'git': opts.get(b'git')}, plain=True)
1385 if opts.get(b'checkname', True):
1376 if opts.get(b'checkname', True):
1386 self.checkpatchname(patchfn)
1377 self.checkpatchname(patchfn)
1387 inclsubs = checksubstate(repo)
1378 inclsubs = checksubstate(repo)
1388 if inclsubs:
1379 if inclsubs:
1389 substatestate = repo.dirstate[b'.hgsubstate']
1380 substatestate = repo.dirstate[b'.hgsubstate']
1390 if opts.get(b'include') or opts.get(b'exclude') or pats:
1381 if opts.get(b'include') or opts.get(b'exclude') or pats:
1391 # detect missing files in pats
1382 # detect missing files in pats
1392 def badfn(f, msg):
1383 def badfn(f, msg):
1393 if f != b'.hgsubstate': # .hgsubstate is auto-created
1384 if f != b'.hgsubstate': # .hgsubstate is auto-created
1394 raise error.Abort(b'%s: %s' % (f, msg))
1385 raise error.Abort(b'%s: %s' % (f, msg))
1395
1386
1396 match = scmutil.match(repo[None], pats, opts, badfn=badfn)
1387 match = scmutil.match(repo[None], pats, opts, badfn=badfn)
1397 changes = repo.status(match=match)
1388 changes = repo.status(match=match)
1398 else:
1389 else:
1399 changes = self.checklocalchanges(repo, force=True)
1390 changes = self.checklocalchanges(repo, force=True)
1400 commitfiles = list(inclsubs)
1391 commitfiles = list(inclsubs)
1401 commitfiles.extend(changes.modified)
1392 commitfiles.extend(changes.modified)
1402 commitfiles.extend(changes.added)
1393 commitfiles.extend(changes.added)
1403 commitfiles.extend(changes.removed)
1394 commitfiles.extend(changes.removed)
1404 match = scmutil.matchfiles(repo, commitfiles)
1395 match = scmutil.matchfiles(repo, commitfiles)
1405 if len(repo[None].parents()) > 1:
1396 if len(repo[None].parents()) > 1:
1406 raise error.Abort(_(b'cannot manage merge changesets'))
1397 raise error.Abort(_(b'cannot manage merge changesets'))
1407 self.checktoppatch(repo)
1398 self.checktoppatch(repo)
1408 insert = self.fullseriesend()
1399 insert = self.fullseriesend()
1409 with repo.wlock():
1400 with repo.wlock():
1410 try:
1401 try:
1411 # if patch file write fails, abort early
1402 # if patch file write fails, abort early
1412 p = self.opener(patchfn, b"w")
1403 p = self.opener(patchfn, b"w")
1413 except IOError as e:
1404 except IOError as e:
1414 raise error.Abort(
1405 raise error.Abort(
1415 _(b'cannot write patch "%s": %s')
1406 _(b'cannot write patch "%s": %s')
1416 % (patchfn, encoding.strtolocal(e.strerror))
1407 % (patchfn, encoding.strtolocal(e.strerror))
1417 )
1408 )
1418 try:
1409 try:
1419 defaultmsg = b"[mq]: %s" % patchfn
1410 defaultmsg = b"[mq]: %s" % patchfn
1420 editor = cmdutil.getcommiteditor(editform=editform)
1411 editor = cmdutil.getcommiteditor(editform=editform)
1421 if edit:
1412 if edit:
1422
1413
1423 def finishdesc(desc):
1414 def finishdesc(desc):
1424 if desc.rstrip():
1415 if desc.rstrip():
1425 return desc
1416 return desc
1426 else:
1417 else:
1427 return defaultmsg
1418 return defaultmsg
1428
1419
1429 # i18n: this message is shown in editor with "HG: " prefix
1420 # i18n: this message is shown in editor with "HG: " prefix
1430 extramsg = _(b'Leave message empty to use default message.')
1421 extramsg = _(b'Leave message empty to use default message.')
1431 editor = cmdutil.getcommiteditor(
1422 editor = cmdutil.getcommiteditor(
1432 finishdesc=finishdesc,
1423 finishdesc=finishdesc,
1433 extramsg=extramsg,
1424 extramsg=extramsg,
1434 editform=editform,
1425 editform=editform,
1435 )
1426 )
1436 commitmsg = msg
1427 commitmsg = msg
1437 else:
1428 else:
1438 commitmsg = msg or defaultmsg
1429 commitmsg = msg or defaultmsg
1439
1430
1440 n = newcommit(
1431 n = newcommit(
1441 repo,
1432 repo,
1442 None,
1433 None,
1443 commitmsg,
1434 commitmsg,
1444 user,
1435 user,
1445 date,
1436 date,
1446 match=match,
1437 match=match,
1447 force=True,
1438 force=True,
1448 editor=editor,
1439 editor=editor,
1449 )
1440 )
1450 if n is None:
1441 if n is None:
1451 raise error.Abort(_(b"repo commit failed"))
1442 raise error.Abort(_(b"repo commit failed"))
1452 try:
1443 try:
1453 self.fullseries[insert:insert] = [patchfn]
1444 self.fullseries[insert:insert] = [patchfn]
1454 self.applied.append(statusentry(n, patchfn))
1445 self.applied.append(statusentry(n, patchfn))
1455 self.parseseries()
1446 self.parseseries()
1456 self.seriesdirty = True
1447 self.seriesdirty = True
1457 self.applieddirty = True
1448 self.applieddirty = True
1458 nctx = repo[n]
1449 nctx = repo[n]
1459 ph = patchheader(self.join(patchfn), self.plainmode)
1450 ph = patchheader(self.join(patchfn), self.plainmode)
1460 if user:
1451 if user:
1461 ph.setuser(user)
1452 ph.setuser(user)
1462 if date:
1453 if date:
1463 ph.setdate(b'%d %d' % date)
1454 ph.setdate(b'%d %d' % date)
1464 ph.setparent(hex(nctx.p1().node()))
1455 ph.setparent(hex(nctx.p1().node()))
1465 msg = nctx.description().strip()
1456 msg = nctx.description().strip()
1466 if msg == defaultmsg.strip():
1457 if msg == defaultmsg.strip():
1467 msg = b''
1458 msg = b''
1468 ph.setmessage(msg)
1459 ph.setmessage(msg)
1469 p.write(bytes(ph))
1460 p.write(bytes(ph))
1470 if commitfiles:
1461 if commitfiles:
1471 parent = self.qparents(repo, n)
1462 parent = self.qparents(repo, n)
1472 if inclsubs:
1463 if inclsubs:
1473 self.putsubstate2changes(substatestate, changes)
1464 self.putsubstate2changes(substatestate, changes)
1474 chunks = patchmod.diff(
1465 chunks = patchmod.diff(
1475 repo,
1466 repo,
1476 node1=parent,
1467 node1=parent,
1477 node2=n,
1468 node2=n,
1478 changes=changes,
1469 changes=changes,
1479 opts=diffopts,
1470 opts=diffopts,
1480 )
1471 )
1481 for chunk in chunks:
1472 for chunk in chunks:
1482 p.write(chunk)
1473 p.write(chunk)
1483 p.close()
1474 p.close()
1484 r = self.qrepo()
1475 r = self.qrepo()
1485 if r:
1476 if r:
1486 r[None].add([patchfn])
1477 r[None].add([patchfn])
1487 except: # re-raises
1478 except: # re-raises
1488 repo.rollback()
1479 repo.rollback()
1489 raise
1480 raise
1490 except Exception:
1481 except Exception:
1491 patchpath = self.join(patchfn)
1482 patchpath = self.join(patchfn)
1492 try:
1483 try:
1493 os.unlink(patchpath)
1484 os.unlink(patchpath)
1494 except OSError:
1485 except OSError:
1495 self.ui.warn(_(b'error unlinking %s\n') % patchpath)
1486 self.ui.warn(_(b'error unlinking %s\n') % patchpath)
1496 raise
1487 raise
1497 self.removeundo(repo)
1488 self.removeundo(repo)
1498
1489
1499 def isapplied(self, patch):
1490 def isapplied(self, patch):
1500 """returns (index, rev, patch)"""
1491 """returns (index, rev, patch)"""
1501 for i, a in enumerate(self.applied):
1492 for i, a in enumerate(self.applied):
1502 if a.name == patch:
1493 if a.name == patch:
1503 return (i, a.node, a.name)
1494 return (i, a.node, a.name)
1504 return None
1495 return None
1505
1496
1506 # if the exact patch name does not exist, we try a few
1497 # if the exact patch name does not exist, we try a few
1507 # variations. If strict is passed, we try only #1
1498 # variations. If strict is passed, we try only #1
1508 #
1499 #
1509 # 1) a number (as string) to indicate an offset in the series file
1500 # 1) a number (as string) to indicate an offset in the series file
1510 # 2) a unique substring of the patch name was given
1501 # 2) a unique substring of the patch name was given
1511 # 3) patchname[-+]num to indicate an offset in the series file
1502 # 3) patchname[-+]num to indicate an offset in the series file
1512 def lookup(self, patch, strict=False):
1503 def lookup(self, patch, strict=False):
1513 def partialname(s):
1504 def partialname(s):
1514 if s in self.series:
1505 if s in self.series:
1515 return s
1506 return s
1516 matches = [x for x in self.series if s in x]
1507 matches = [x for x in self.series if s in x]
1517 if len(matches) > 1:
1508 if len(matches) > 1:
1518 self.ui.warn(_(b'patch name "%s" is ambiguous:\n') % s)
1509 self.ui.warn(_(b'patch name "%s" is ambiguous:\n') % s)
1519 for m in matches:
1510 for m in matches:
1520 self.ui.warn(b' %s\n' % m)
1511 self.ui.warn(b' %s\n' % m)
1521 return None
1512 return None
1522 if matches:
1513 if matches:
1523 return matches[0]
1514 return matches[0]
1524 if self.series and self.applied:
1515 if self.series and self.applied:
1525 if s == b'qtip':
1516 if s == b'qtip':
1526 return self.series[self.seriesend(True) - 1]
1517 return self.series[self.seriesend(True) - 1]
1527 if s == b'qbase':
1518 if s == b'qbase':
1528 return self.series[0]
1519 return self.series[0]
1529 return None
1520 return None
1530
1521
1531 if patch in self.series:
1522 if patch in self.series:
1532 return patch
1523 return patch
1533
1524
1534 if not os.path.isfile(self.join(patch)):
1525 if not os.path.isfile(self.join(patch)):
1535 try:
1526 try:
1536 sno = int(patch)
1527 sno = int(patch)
1537 except (ValueError, OverflowError):
1528 except (ValueError, OverflowError):
1538 pass
1529 pass
1539 else:
1530 else:
1540 if -len(self.series) <= sno < len(self.series):
1531 if -len(self.series) <= sno < len(self.series):
1541 return self.series[sno]
1532 return self.series[sno]
1542
1533
1543 if not strict:
1534 if not strict:
1544 res = partialname(patch)
1535 res = partialname(patch)
1545 if res:
1536 if res:
1546 return res
1537 return res
1547 minus = patch.rfind(b'-')
1538 minus = patch.rfind(b'-')
1548 if minus >= 0:
1539 if minus >= 0:
1549 res = partialname(patch[:minus])
1540 res = partialname(patch[:minus])
1550 if res:
1541 if res:
1551 i = self.series.index(res)
1542 i = self.series.index(res)
1552 try:
1543 try:
1553 off = int(patch[minus + 1 :] or 1)
1544 off = int(patch[minus + 1 :] or 1)
1554 except (ValueError, OverflowError):
1545 except (ValueError, OverflowError):
1555 pass
1546 pass
1556 else:
1547 else:
1557 if i - off >= 0:
1548 if i - off >= 0:
1558 return self.series[i - off]
1549 return self.series[i - off]
1559 plus = patch.rfind(b'+')
1550 plus = patch.rfind(b'+')
1560 if plus >= 0:
1551 if plus >= 0:
1561 res = partialname(patch[:plus])
1552 res = partialname(patch[:plus])
1562 if res:
1553 if res:
1563 i = self.series.index(res)
1554 i = self.series.index(res)
1564 try:
1555 try:
1565 off = int(patch[plus + 1 :] or 1)
1556 off = int(patch[plus + 1 :] or 1)
1566 except (ValueError, OverflowError):
1557 except (ValueError, OverflowError):
1567 pass
1558 pass
1568 else:
1559 else:
1569 if i + off < len(self.series):
1560 if i + off < len(self.series):
1570 return self.series[i + off]
1561 return self.series[i + off]
1571 raise error.Abort(_(b"patch %s not in series") % patch)
1562 raise error.Abort(_(b"patch %s not in series") % patch)
1572
1563
1573 def push(
1564 def push(
1574 self,
1565 self,
1575 repo,
1566 repo,
1576 patch=None,
1567 patch=None,
1577 force=False,
1568 force=False,
1578 list=False,
1569 list=False,
1579 mergeq=None,
1570 mergeq=None,
1580 all=False,
1571 all=False,
1581 move=False,
1572 move=False,
1582 exact=False,
1573 exact=False,
1583 nobackup=False,
1574 nobackup=False,
1584 keepchanges=False,
1575 keepchanges=False,
1585 ):
1576 ):
1586 self.checkkeepchanges(keepchanges, force)
1577 self.checkkeepchanges(keepchanges, force)
1587 diffopts = self.diffopts()
1578 diffopts = self.diffopts()
1588 with repo.wlock():
1579 with repo.wlock():
1589 heads = []
1580 heads = []
1590 for hs in repo.branchmap().iterheads():
1581 for hs in repo.branchmap().iterheads():
1591 heads.extend(hs)
1582 heads.extend(hs)
1592 if not heads:
1583 if not heads:
1593 heads = [repo.nullid]
1584 heads = [repo.nullid]
1594 if repo.dirstate.p1() not in heads and not exact:
1585 if repo.dirstate.p1() not in heads and not exact:
1595 self.ui.status(_(b"(working directory not at a head)\n"))
1586 self.ui.status(_(b"(working directory not at a head)\n"))
1596
1587
1597 if not self.series:
1588 if not self.series:
1598 self.ui.warn(_(b'no patches in series\n'))
1589 self.ui.warn(_(b'no patches in series\n'))
1599 return 0
1590 return 0
1600
1591
1601 # Suppose our series file is: A B C and the current 'top'
1592 # Suppose our series file is: A B C and the current 'top'
1602 # patch is B. qpush C should be performed (moving forward)
1593 # patch is B. qpush C should be performed (moving forward)
1603 # qpush B is a NOP (no change) qpush A is an error (can't
1594 # qpush B is a NOP (no change) qpush A is an error (can't
1604 # go backwards with qpush)
1595 # go backwards with qpush)
1605 if patch:
1596 if patch:
1606 patch = self.lookup(patch)
1597 patch = self.lookup(patch)
1607 info = self.isapplied(patch)
1598 info = self.isapplied(patch)
1608 if info and info[0] >= len(self.applied) - 1:
1599 if info and info[0] >= len(self.applied) - 1:
1609 self.ui.warn(
1600 self.ui.warn(
1610 _(b'qpush: %s is already at the top\n') % patch
1601 _(b'qpush: %s is already at the top\n') % patch
1611 )
1602 )
1612 return 0
1603 return 0
1613
1604
1614 pushable, reason = self.pushable(patch)
1605 pushable, reason = self.pushable(patch)
1615 if pushable:
1606 if pushable:
1616 if self.series.index(patch) < self.seriesend():
1607 if self.series.index(patch) < self.seriesend():
1617 raise error.Abort(
1608 raise error.Abort(
1618 _(b"cannot push to a previous patch: %s") % patch
1609 _(b"cannot push to a previous patch: %s") % patch
1619 )
1610 )
1620 else:
1611 else:
1621 if reason:
1612 if reason:
1622 reason = _(b'guarded by %s') % reason
1613 reason = _(b'guarded by %s') % reason
1623 else:
1614 else:
1624 reason = _(b'no matching guards')
1615 reason = _(b'no matching guards')
1625 self.ui.warn(
1616 self.ui.warn(
1626 _(b"cannot push '%s' - %s\n") % (patch, reason)
1617 _(b"cannot push '%s' - %s\n") % (patch, reason)
1627 )
1618 )
1628 return 1
1619 return 1
1629 elif all:
1620 elif all:
1630 patch = self.series[-1]
1621 patch = self.series[-1]
1631 if self.isapplied(patch):
1622 if self.isapplied(patch):
1632 self.ui.warn(_(b'all patches are currently applied\n'))
1623 self.ui.warn(_(b'all patches are currently applied\n'))
1633 return 0
1624 return 0
1634
1625
1635 # Following the above example, starting at 'top' of B:
1626 # Following the above example, starting at 'top' of B:
1636 # qpush should be performed (pushes C), but a subsequent
1627 # qpush should be performed (pushes C), but a subsequent
1637 # qpush without an argument is an error (nothing to
1628 # qpush without an argument is an error (nothing to
1638 # apply). This allows a loop of "...while hg qpush..." to
1629 # apply). This allows a loop of "...while hg qpush..." to
1639 # work as it detects an error when done
1630 # work as it detects an error when done
1640 start = self.seriesend()
1631 start = self.seriesend()
1641 if start == len(self.series):
1632 if start == len(self.series):
1642 self.ui.warn(_(b'patch series already fully applied\n'))
1633 self.ui.warn(_(b'patch series already fully applied\n'))
1643 return 1
1634 return 1
1644 if not force and not keepchanges:
1635 if not force and not keepchanges:
1645 self.checklocalchanges(repo, refresh=self.applied)
1636 self.checklocalchanges(repo, refresh=self.applied)
1646
1637
1647 if exact:
1638 if exact:
1648 if keepchanges:
1639 if keepchanges:
1649 raise error.Abort(
1640 raise error.Abort(
1650 _(b"cannot use --exact and --keep-changes together")
1641 _(b"cannot use --exact and --keep-changes together")
1651 )
1642 )
1652 if move:
1643 if move:
1653 raise error.Abort(
1644 raise error.Abort(
1654 _(b'cannot use --exact and --move together')
1645 _(b'cannot use --exact and --move together')
1655 )
1646 )
1656 if self.applied:
1647 if self.applied:
1657 raise error.Abort(
1648 raise error.Abort(
1658 _(b'cannot push --exact with applied patches')
1649 _(b'cannot push --exact with applied patches')
1659 )
1650 )
1660 root = self.series[start]
1651 root = self.series[start]
1661 target = patchheader(self.join(root), self.plainmode).parent
1652 target = patchheader(self.join(root), self.plainmode).parent
1662 if not target:
1653 if not target:
1663 raise error.Abort(
1654 raise error.Abort(
1664 _(b"%s does not have a parent recorded") % root
1655 _(b"%s does not have a parent recorded") % root
1665 )
1656 )
1666 if not repo[target] == repo[b'.']:
1657 if not repo[target] == repo[b'.']:
1667 hg.update(repo, target)
1658 hg.update(repo, target)
1668
1659
1669 if move:
1660 if move:
1670 if not patch:
1661 if not patch:
1671 raise error.Abort(_(b"please specify the patch to move"))
1662 raise error.Abort(_(b"please specify the patch to move"))
1672 for fullstart, rpn in enumerate(self.fullseries):
1663 for fullstart, rpn in enumerate(self.fullseries):
1673 # strip markers for patch guards
1664 # strip markers for patch guards
1674 if self.guard_re.split(rpn, 1)[0] == self.series[start]:
1665 if self.guard_re.split(rpn, 1)[0] == self.series[start]:
1675 break
1666 break
1676 for i, rpn in enumerate(self.fullseries[fullstart:]):
1667 for i, rpn in enumerate(self.fullseries[fullstart:]):
1677 # strip markers for patch guards
1668 # strip markers for patch guards
1678 if self.guard_re.split(rpn, 1)[0] == patch:
1669 if self.guard_re.split(rpn, 1)[0] == patch:
1679 break
1670 break
1680 index = fullstart + i
1671 index = fullstart + i
1681 assert index < len(self.fullseries)
1672 assert index < len(self.fullseries)
1682 fullpatch = self.fullseries[index]
1673 fullpatch = self.fullseries[index]
1683 del self.fullseries[index]
1674 del self.fullseries[index]
1684 self.fullseries.insert(fullstart, fullpatch)
1675 self.fullseries.insert(fullstart, fullpatch)
1685 self.parseseries()
1676 self.parseseries()
1686 self.seriesdirty = True
1677 self.seriesdirty = True
1687
1678
1688 self.applieddirty = True
1679 self.applieddirty = True
1689 if start > 0:
1680 if start > 0:
1690 self.checktoppatch(repo)
1681 self.checktoppatch(repo)
1691 if not patch:
1682 if not patch:
1692 patch = self.series[start]
1683 patch = self.series[start]
1693 end = start + 1
1684 end = start + 1
1694 else:
1685 else:
1695 end = self.series.index(patch, start) + 1
1686 end = self.series.index(patch, start) + 1
1696
1687
1697 tobackup = set()
1688 tobackup = set()
1698 if (not nobackup and force) or keepchanges:
1689 if (not nobackup and force) or keepchanges:
1699 status = self.checklocalchanges(repo, force=True)
1690 status = self.checklocalchanges(repo, force=True)
1700 if keepchanges:
1691 if keepchanges:
1701 tobackup.update(
1692 tobackup.update(
1702 status.modified
1693 status.modified
1703 + status.added
1694 + status.added
1704 + status.removed
1695 + status.removed
1705 + status.deleted
1696 + status.deleted
1706 )
1697 )
1707 else:
1698 else:
1708 tobackup.update(status.modified + status.added)
1699 tobackup.update(status.modified + status.added)
1709
1700
1710 s = self.series[start:end]
1701 s = self.series[start:end]
1711 all_files = set()
1702 all_files = set()
1712 try:
1703 try:
1713 if mergeq:
1704 if mergeq:
1714 ret = self.mergepatch(repo, mergeq, s, diffopts)
1705 ret = self.mergepatch(repo, mergeq, s, diffopts)
1715 else:
1706 else:
1716 ret = self.apply(
1707 ret = self.apply(
1717 repo,
1708 repo,
1718 s,
1709 s,
1719 list,
1710 list,
1720 all_files=all_files,
1711 all_files=all_files,
1721 tobackup=tobackup,
1712 tobackup=tobackup,
1722 keepchanges=keepchanges,
1713 keepchanges=keepchanges,
1723 )
1714 )
1724 except AbortNoCleanup:
1715 except AbortNoCleanup:
1725 raise
1716 raise
1726 except: # re-raises
1717 except: # re-raises
1727 self.ui.warn(_(b'cleaning up working directory...\n'))
1718 self.ui.warn(_(b'cleaning up working directory...\n'))
1728 cmdutil.revert(
1719 cmdutil.revert(
1729 self.ui,
1720 self.ui,
1730 repo,
1721 repo,
1731 repo[b'.'],
1722 repo[b'.'],
1732 no_backup=True,
1723 no_backup=True,
1733 )
1724 )
1734 # only remove unknown files that we know we touched or
1725 # only remove unknown files that we know we touched or
1735 # created while patching
1726 # created while patching
1736 for f in all_files:
1727 for f in all_files:
1737 if f not in repo.dirstate:
1728 if f not in repo.dirstate:
1738 repo.wvfs.unlinkpath(f, ignoremissing=True)
1729 repo.wvfs.unlinkpath(f, ignoremissing=True)
1739 self.ui.warn(_(b'done\n'))
1730 self.ui.warn(_(b'done\n'))
1740 raise
1731 raise
1741
1732
1742 if not self.applied:
1733 if not self.applied:
1743 return ret[0]
1734 return ret[0]
1744 top = self.applied[-1].name
1735 top = self.applied[-1].name
1745 if ret[0] and ret[0] > 1:
1736 if ret[0] and ret[0] > 1:
1746 msg = _(b"errors during apply, please fix and qrefresh %s\n")
1737 msg = _(b"errors during apply, please fix and qrefresh %s\n")
1747 self.ui.write(msg % top)
1738 self.ui.write(msg % top)
1748 else:
1739 else:
1749 self.ui.write(_(b"now at: %s\n") % top)
1740 self.ui.write(_(b"now at: %s\n") % top)
1750 return ret[0]
1741 return ret[0]
1751
1742
1752 def pop(
1743 def pop(
1753 self,
1744 self,
1754 repo,
1745 repo,
1755 patch=None,
1746 patch=None,
1756 force=False,
1747 force=False,
1757 update=True,
1748 update=True,
1758 all=False,
1749 all=False,
1759 nobackup=False,
1750 nobackup=False,
1760 keepchanges=False,
1751 keepchanges=False,
1761 ):
1752 ):
1762 self.checkkeepchanges(keepchanges, force)
1753 self.checkkeepchanges(keepchanges, force)
1763 with repo.wlock():
1754 with repo.wlock():
1764 if patch:
1755 if patch:
1765 # index, rev, patch
1756 # index, rev, patch
1766 info = self.isapplied(patch)
1757 info = self.isapplied(patch)
1767 if not info:
1758 if not info:
1768 patch = self.lookup(patch)
1759 patch = self.lookup(patch)
1769 info = self.isapplied(patch)
1760 info = self.isapplied(patch)
1770 if not info:
1761 if not info:
1771 raise error.Abort(_(b"patch %s is not applied") % patch)
1762 raise error.Abort(_(b"patch %s is not applied") % patch)
1772
1763
1773 if not self.applied:
1764 if not self.applied:
1774 # Allow qpop -a to work repeatedly,
1765 # Allow qpop -a to work repeatedly,
1775 # but not qpop without an argument
1766 # but not qpop without an argument
1776 self.ui.warn(_(b"no patches applied\n"))
1767 self.ui.warn(_(b"no patches applied\n"))
1777 return not all
1768 return not all
1778
1769
1779 if all:
1770 if all:
1780 start = 0
1771 start = 0
1781 elif patch:
1772 elif patch:
1782 start = info[0] + 1
1773 start = info[0] + 1
1783 else:
1774 else:
1784 start = len(self.applied) - 1
1775 start = len(self.applied) - 1
1785
1776
1786 if start >= len(self.applied):
1777 if start >= len(self.applied):
1787 self.ui.warn(_(b"qpop: %s is already at the top\n") % patch)
1778 self.ui.warn(_(b"qpop: %s is already at the top\n") % patch)
1788 return
1779 return
1789
1780
1790 if not update:
1781 if not update:
1791 parents = repo.dirstate.parents()
1782 parents = repo.dirstate.parents()
1792 rr = [x.node for x in self.applied]
1783 rr = [x.node for x in self.applied]
1793 for p in parents:
1784 for p in parents:
1794 if p in rr:
1785 if p in rr:
1795 self.ui.warn(_(b"qpop: forcing dirstate update\n"))
1786 self.ui.warn(_(b"qpop: forcing dirstate update\n"))
1796 update = True
1787 update = True
1797 else:
1788 else:
1798 parents = [p.node() for p in repo[None].parents()]
1789 parents = [p.node() for p in repo[None].parents()]
1799 update = any(
1790 update = any(
1800 entry.node in parents for entry in self.applied[start:]
1791 entry.node in parents for entry in self.applied[start:]
1801 )
1792 )
1802
1793
1803 tobackup = set()
1794 tobackup = set()
1804 if update:
1795 if update:
1805 s = self.checklocalchanges(repo, force=force or keepchanges)
1796 s = self.checklocalchanges(repo, force=force or keepchanges)
1806 if force:
1797 if force:
1807 if not nobackup:
1798 if not nobackup:
1808 tobackup.update(s.modified + s.added)
1799 tobackup.update(s.modified + s.added)
1809 elif keepchanges:
1800 elif keepchanges:
1810 tobackup.update(
1801 tobackup.update(
1811 s.modified + s.added + s.removed + s.deleted
1802 s.modified + s.added + s.removed + s.deleted
1812 )
1803 )
1813
1804
1814 self.applieddirty = True
1805 self.applieddirty = True
1815 end = len(self.applied)
1806 end = len(self.applied)
1816 rev = self.applied[start].node
1807 rev = self.applied[start].node
1817
1808
1818 try:
1809 try:
1819 heads = repo.changelog.heads(rev)
1810 heads = repo.changelog.heads(rev)
1820 except error.LookupError:
1811 except error.LookupError:
1821 node = short(rev)
1812 node = short(rev)
1822 raise error.Abort(_(b'trying to pop unknown node %s') % node)
1813 raise error.Abort(_(b'trying to pop unknown node %s') % node)
1823
1814
1824 if heads != [self.applied[-1].node]:
1815 if heads != [self.applied[-1].node]:
1825 raise error.Abort(
1816 raise error.Abort(
1826 _(
1817 _(
1827 b"popping would remove a revision not "
1818 b"popping would remove a revision not "
1828 b"managed by this patch queue"
1819 b"managed by this patch queue"
1829 )
1820 )
1830 )
1821 )
1831 if not repo[self.applied[-1].node].mutable():
1822 if not repo[self.applied[-1].node].mutable():
1832 raise error.Abort(
1823 raise error.Abort(
1833 _(b"popping would remove a public revision"),
1824 _(b"popping would remove a public revision"),
1834 hint=_(b"see 'hg help phases' for details"),
1825 hint=_(b"see 'hg help phases' for details"),
1835 )
1826 )
1836
1827
1837 # we know there are no local changes, so we can make a simplified
1828 # we know there are no local changes, so we can make a simplified
1838 # form of hg.update.
1829 # form of hg.update.
1839 if update:
1830 if update:
1840 qp = self.qparents(repo, rev)
1831 qp = self.qparents(repo, rev)
1841 ctx = repo[qp]
1832 ctx = repo[qp]
1842 st = repo.status(qp, b'.')
1833 st = repo.status(qp, b'.')
1843 m, a, r, d = st.modified, st.added, st.removed, st.deleted
1834 m, a, r, d = st.modified, st.added, st.removed, st.deleted
1844 if d:
1835 if d:
1845 raise error.Abort(_(b"deletions found between repo revs"))
1836 raise error.Abort(_(b"deletions found between repo revs"))
1846
1837
1847 tobackup = set(a + m + r) & tobackup
1838 tobackup = set(a + m + r) & tobackup
1848 if keepchanges and tobackup:
1839 if keepchanges and tobackup:
1849 raise error.Abort(_(b"local changes found, qrefresh first"))
1840 raise error.Abort(_(b"local changes found, qrefresh first"))
1850 self.backup(repo, tobackup)
1841 self.backup(repo, tobackup)
1851 with repo.dirstate.parentchange():
1842 with repo.dirstate.parentchange():
1852 for f in a:
1843 for f in a:
1853 repo.wvfs.unlinkpath(f, ignoremissing=True)
1844 repo.wvfs.unlinkpath(f, ignoremissing=True)
1854 repo.dirstate.drop(f)
1845 repo.dirstate.drop(f)
1855 for f in m + r:
1846 for f in m + r:
1856 fctx = ctx[f]
1847 fctx = ctx[f]
1857 repo.wwrite(f, fctx.data(), fctx.flags())
1848 repo.wwrite(f, fctx.data(), fctx.flags())
1858 repo.dirstate.update_file(
1849 repo.dirstate.update_file(
1859 f, p1_tracked=True, wc_tracked=True
1850 f, p1_tracked=True, wc_tracked=True
1860 )
1851 )
1861 repo.setparents(qp, repo.nullid)
1852 repo.setparents(qp, repo.nullid)
1862 for patch in reversed(self.applied[start:end]):
1853 for patch in reversed(self.applied[start:end]):
1863 self.ui.status(_(b"popping %s\n") % patch.name)
1854 self.ui.status(_(b"popping %s\n") % patch.name)
1864 del self.applied[start:end]
1855 del self.applied[start:end]
1865 strip(self.ui, repo, [rev], update=False, backup=False)
1856 strip(self.ui, repo, [rev], update=False, backup=False)
1866 for s, state in repo[b'.'].substate.items():
1857 for s, state in repo[b'.'].substate.items():
1867 repo[b'.'].sub(s).get(state)
1858 repo[b'.'].sub(s).get(state)
1868 if self.applied:
1859 if self.applied:
1869 self.ui.write(_(b"now at: %s\n") % self.applied[-1].name)
1860 self.ui.write(_(b"now at: %s\n") % self.applied[-1].name)
1870 else:
1861 else:
1871 self.ui.write(_(b"patch queue now empty\n"))
1862 self.ui.write(_(b"patch queue now empty\n"))
1872
1863
1873 def diff(self, repo, pats, opts):
1864 def diff(self, repo, pats, opts):
1874 top, patch = self.checktoppatch(repo)
1865 top, patch = self.checktoppatch(repo)
1875 if not top:
1866 if not top:
1876 self.ui.write(_(b"no patches applied\n"))
1867 self.ui.write(_(b"no patches applied\n"))
1877 return
1868 return
1878 qp = self.qparents(repo, top)
1869 qp = self.qparents(repo, top)
1879 if opts.get(b'reverse'):
1870 if opts.get(b'reverse'):
1880 node1, node2 = None, qp
1871 node1, node2 = None, qp
1881 else:
1872 else:
1882 node1, node2 = qp, None
1873 node1, node2 = qp, None
1883 diffopts = self.diffopts(opts, patch)
1874 diffopts = self.diffopts(opts, patch)
1884 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1875 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1885
1876
1886 def refresh(self, repo, pats=None, **opts):
1877 def refresh(self, repo, pats=None, **opts):
1887 opts = pycompat.byteskwargs(opts)
1878 opts = pycompat.byteskwargs(opts)
1888 if not self.applied:
1879 if not self.applied:
1889 self.ui.write(_(b"no patches applied\n"))
1880 self.ui.write(_(b"no patches applied\n"))
1890 return 1
1881 return 1
1891 msg = opts.get(b'msg', b'').rstrip()
1882 msg = opts.get(b'msg', b'').rstrip()
1892 edit = opts.get(b'edit')
1883 edit = opts.get(b'edit')
1893 editform = opts.get(b'editform', b'mq.qrefresh')
1884 editform = opts.get(b'editform', b'mq.qrefresh')
1894 newuser = opts.get(b'user')
1885 newuser = opts.get(b'user')
1895 newdate = opts.get(b'date')
1886 newdate = opts.get(b'date')
1896 if newdate:
1887 if newdate:
1897 newdate = b'%d %d' % dateutil.parsedate(newdate)
1888 newdate = b'%d %d' % dateutil.parsedate(newdate)
1898 wlock = repo.wlock()
1889 wlock = repo.wlock()
1899
1890
1900 try:
1891 try:
1901 self.checktoppatch(repo)
1892 self.checktoppatch(repo)
1902 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1893 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1903 if repo.changelog.heads(top) != [top]:
1894 if repo.changelog.heads(top) != [top]:
1904 raise error.Abort(
1895 raise error.Abort(
1905 _(b"cannot qrefresh a revision with children")
1896 _(b"cannot qrefresh a revision with children")
1906 )
1897 )
1907 if not repo[top].mutable():
1898 if not repo[top].mutable():
1908 raise error.Abort(
1899 raise error.Abort(
1909 _(b"cannot qrefresh public revision"),
1900 _(b"cannot qrefresh public revision"),
1910 hint=_(b"see 'hg help phases' for details"),
1901 hint=_(b"see 'hg help phases' for details"),
1911 )
1902 )
1912
1903
1913 cparents = repo.changelog.parents(top)
1904 cparents = repo.changelog.parents(top)
1914 patchparent = self.qparents(repo, top)
1905 patchparent = self.qparents(repo, top)
1915
1906
1916 inclsubs = checksubstate(repo, patchparent)
1907 inclsubs = checksubstate(repo, patchparent)
1917 if inclsubs:
1908 if inclsubs:
1918 substatestate = repo.dirstate[b'.hgsubstate']
1909 substatestate = repo.dirstate[b'.hgsubstate']
1919
1910
1920 ph = patchheader(self.join(patchfn), self.plainmode)
1911 ph = patchheader(self.join(patchfn), self.plainmode)
1921 diffopts = self.diffopts(
1912 diffopts = self.diffopts(
1922 {b'git': opts.get(b'git')}, patchfn, plain=True
1913 {b'git': opts.get(b'git')}, patchfn, plain=True
1923 )
1914 )
1924 if newuser:
1915 if newuser:
1925 ph.setuser(newuser)
1916 ph.setuser(newuser)
1926 if newdate:
1917 if newdate:
1927 ph.setdate(newdate)
1918 ph.setdate(newdate)
1928 ph.setparent(hex(patchparent))
1919 ph.setparent(hex(patchparent))
1929
1920
1930 # only commit new patch when write is complete
1921 # only commit new patch when write is complete
1931 patchf = self.opener(patchfn, b'w', atomictemp=True)
1922 patchf = self.opener(patchfn, b'w', atomictemp=True)
1932
1923
1933 # update the dirstate in place, strip off the qtip commit
1924 # update the dirstate in place, strip off the qtip commit
1934 # and then commit.
1925 # and then commit.
1935 #
1926 #
1936 # this should really read:
1927 # this should really read:
1937 # st = repo.status(top, patchparent)
1928 # st = repo.status(top, patchparent)
1938 # but we do it backwards to take advantage of manifest/changelog
1929 # but we do it backwards to take advantage of manifest/changelog
1939 # caching against the next repo.status call
1930 # caching against the next repo.status call
1940 st = repo.status(patchparent, top)
1931 st = repo.status(patchparent, top)
1941 mm, aa, dd = st.modified, st.added, st.removed
1932 mm, aa, dd = st.modified, st.added, st.removed
1942 ctx = repo[top]
1933 ctx = repo[top]
1943 aaa = aa[:]
1934 aaa = aa[:]
1944 match1 = scmutil.match(repo[None], pats, opts)
1935 match1 = scmutil.match(repo[None], pats, opts)
1945 # in short mode, we only diff the files included in the
1936 # in short mode, we only diff the files included in the
1946 # patch already plus specified files
1937 # patch already plus specified files
1947 if opts.get(b'short'):
1938 if opts.get(b'short'):
1948 # if amending a patch, we start with existing
1939 # if amending a patch, we start with existing
1949 # files plus specified files - unfiltered
1940 # files plus specified files - unfiltered
1950 match = scmutil.matchfiles(repo, mm + aa + dd + match1.files())
1941 match = scmutil.matchfiles(repo, mm + aa + dd + match1.files())
1951 # filter with include/exclude options
1942 # filter with include/exclude options
1952 match1 = scmutil.match(repo[None], opts=opts)
1943 match1 = scmutil.match(repo[None], opts=opts)
1953 else:
1944 else:
1954 match = scmutil.matchall(repo)
1945 match = scmutil.matchall(repo)
1955 stb = repo.status(match=match)
1946 stb = repo.status(match=match)
1956 m, a, r, d = stb.modified, stb.added, stb.removed, stb.deleted
1947 m, a, r, d = stb.modified, stb.added, stb.removed, stb.deleted
1957 mm = set(mm)
1948 mm = set(mm)
1958 aa = set(aa)
1949 aa = set(aa)
1959 dd = set(dd)
1950 dd = set(dd)
1960
1951
1961 # we might end up with files that were added between
1952 # we might end up with files that were added between
1962 # qtip and the dirstate parent, but then changed in the
1953 # qtip and the dirstate parent, but then changed in the
1963 # local dirstate. in this case, we want them to only
1954 # local dirstate. in this case, we want them to only
1964 # show up in the added section
1955 # show up in the added section
1965 for x in m:
1956 for x in m:
1966 if x not in aa:
1957 if x not in aa:
1967 mm.add(x)
1958 mm.add(x)
1968 # we might end up with files added by the local dirstate that
1959 # we might end up with files added by the local dirstate that
1969 # were deleted by the patch. In this case, they should only
1960 # were deleted by the patch. In this case, they should only
1970 # show up in the changed section.
1961 # show up in the changed section.
1971 for x in a:
1962 for x in a:
1972 if x in dd:
1963 if x in dd:
1973 dd.remove(x)
1964 dd.remove(x)
1974 mm.add(x)
1965 mm.add(x)
1975 else:
1966 else:
1976 aa.add(x)
1967 aa.add(x)
1977 # make sure any files deleted in the local dirstate
1968 # make sure any files deleted in the local dirstate
1978 # are not in the add or change column of the patch
1969 # are not in the add or change column of the patch
1979 forget = []
1970 forget = []
1980 for x in d + r:
1971 for x in d + r:
1981 if x in aa:
1972 if x in aa:
1982 aa.remove(x)
1973 aa.remove(x)
1983 forget.append(x)
1974 forget.append(x)
1984 continue
1975 continue
1985 else:
1976 else:
1986 mm.discard(x)
1977 mm.discard(x)
1987 dd.add(x)
1978 dd.add(x)
1988
1979
1989 m = list(mm)
1980 m = list(mm)
1990 r = list(dd)
1981 r = list(dd)
1991 a = list(aa)
1982 a = list(aa)
1992
1983
1993 # create 'match' that includes the files to be recommitted.
1984 # create 'match' that includes the files to be recommitted.
1994 # apply match1 via repo.status to ensure correct case handling.
1985 # apply match1 via repo.status to ensure correct case handling.
1995 st = repo.status(patchparent, match=match1)
1986 st = repo.status(patchparent, match=match1)
1996 cm, ca, cr, cd = st.modified, st.added, st.removed, st.deleted
1987 cm, ca, cr, cd = st.modified, st.added, st.removed, st.deleted
1997 allmatches = set(cm + ca + cr + cd)
1988 allmatches = set(cm + ca + cr + cd)
1998 refreshchanges = [x.intersection(allmatches) for x in (mm, aa, dd)]
1989 refreshchanges = [x.intersection(allmatches) for x in (mm, aa, dd)]
1999
1990
2000 files = set(inclsubs)
1991 files = set(inclsubs)
2001 for x in refreshchanges:
1992 for x in refreshchanges:
2002 files.update(x)
1993 files.update(x)
2003 match = scmutil.matchfiles(repo, files)
1994 match = scmutil.matchfiles(repo, files)
2004
1995
2005 bmlist = repo[top].bookmarks()
1996 bmlist = repo[top].bookmarks()
2006
1997
2007 with repo.dirstate.parentchange():
1998 with repo.dirstate.parentchange():
2008 # XXX do we actually need the dirstateguard
1999 # XXX do we actually need the dirstateguard
2009 dsguard = None
2000 dsguard = None
2010 try:
2001 try:
2011 dsguard = dirstateguard.dirstateguard(repo, b'mq.refresh')
2002 dsguard = dirstateguard.dirstateguard(repo, b'mq.refresh')
2012 if diffopts.git or diffopts.upgrade:
2003 if diffopts.git or diffopts.upgrade:
2013 copies = {}
2004 copies = {}
2014 for dst in a:
2005 for dst in a:
2015 src = repo.dirstate.copied(dst)
2006 src = repo.dirstate.copied(dst)
2016 # during qfold, the source file for copies may
2007 # during qfold, the source file for copies may
2017 # be removed. Treat this as a simple add.
2008 # be removed. Treat this as a simple add.
2018 if src is not None and src in repo.dirstate:
2009 if src is not None and src in repo.dirstate:
2019 copies.setdefault(src, []).append(dst)
2010 copies.setdefault(src, []).append(dst)
2020 repo.dirstate.add(dst)
2011 repo.dirstate.add(dst)
2021 # remember the copies between patchparent and qtip
2012 # remember the copies between patchparent and qtip
2022 for dst in aaa:
2013 for dst in aaa:
2023 src = ctx[dst].copysource()
2014 src = ctx[dst].copysource()
2024 if src:
2015 if src:
2025 copies.setdefault(src, []).extend(
2016 copies.setdefault(src, []).extend(
2026 copies.get(dst, [])
2017 copies.get(dst, [])
2027 )
2018 )
2028 if dst in a:
2019 if dst in a:
2029 copies[src].append(dst)
2020 copies[src].append(dst)
2030 # we can't copy a file created by the patch itself
2021 # we can't copy a file created by the patch itself
2031 if dst in copies:
2022 if dst in copies:
2032 del copies[dst]
2023 del copies[dst]
2033 for src, dsts in pycompat.iteritems(copies):
2024 for src, dsts in pycompat.iteritems(copies):
2034 for dst in dsts:
2025 for dst in dsts:
2035 repo.dirstate.copy(src, dst)
2026 repo.dirstate.copy(src, dst)
2036 else:
2027 else:
2037 for dst in a:
2028 for dst in a:
2038 repo.dirstate.add(dst)
2029 repo.dirstate.add(dst)
2039 # Drop useless copy information
2030 # Drop useless copy information
2040 for f in list(repo.dirstate.copies()):
2031 for f in list(repo.dirstate.copies()):
2041 repo.dirstate.copy(None, f)
2032 repo.dirstate.copy(None, f)
2042 for f in r:
2033 for f in r:
2043 repo.dirstate.update_file_p1(f, p1_tracked=True)
2034 repo.dirstate.update_file_p1(f, p1_tracked=True)
2044 # if the patch excludes a modified file, mark that
2035 # if the patch excludes a modified file, mark that
2045 # file with mtime=0 so status can see it.
2036 # file with mtime=0 so status can see it.
2046 mm = []
2037 mm = []
2047 for i in pycompat.xrange(len(m) - 1, -1, -1):
2038 for i in pycompat.xrange(len(m) - 1, -1, -1):
2048 if not match1(m[i]):
2039 if not match1(m[i]):
2049 mm.append(m[i])
2040 mm.append(m[i])
2050 del m[i]
2041 del m[i]
2051 for f in m:
2042 for f in m:
2052 repo.dirstate.update_file_p1(f, p1_tracked=True)
2043 repo.dirstate.update_file_p1(f, p1_tracked=True)
2053 for f in mm:
2044 for f in mm:
2054 repo.dirstate.update_file_p1(f, p1_tracked=True)
2045 repo.dirstate.update_file_p1(f, p1_tracked=True)
2055 for f in forget:
2046 for f in forget:
2056 repo.dirstate.drop(f)
2047 repo.dirstate.drop(f)
2057
2048
2058 user = ph.user or ctx.user()
2049 user = ph.user or ctx.user()
2059
2050
2060 oldphase = repo[top].phase()
2051 oldphase = repo[top].phase()
2061
2052
2062 # assumes strip can roll itself back if interrupted
2053 # assumes strip can roll itself back if interrupted
2063 repo.setparents(*cparents)
2054 repo.setparents(*cparents)
2064 self.applied.pop()
2055 self.applied.pop()
2065 self.applieddirty = True
2056 self.applieddirty = True
2066 strip(self.ui, repo, [top], update=False, backup=False)
2057 strip(self.ui, repo, [top], update=False, backup=False)
2067 dsguard.close()
2058 dsguard.close()
2068 finally:
2059 finally:
2069 release(dsguard)
2060 release(dsguard)
2070
2061
2071 try:
2062 try:
2072 # might be nice to attempt to roll back strip after this
2063 # might be nice to attempt to roll back strip after this
2073
2064
2074 defaultmsg = b"[mq]: %s" % patchfn
2065 defaultmsg = b"[mq]: %s" % patchfn
2075 editor = cmdutil.getcommiteditor(editform=editform)
2066 editor = cmdutil.getcommiteditor(editform=editform)
2076 if edit:
2067 if edit:
2077
2068
2078 def finishdesc(desc):
2069 def finishdesc(desc):
2079 if desc.rstrip():
2070 if desc.rstrip():
2080 ph.setmessage(desc)
2071 ph.setmessage(desc)
2081 return desc
2072 return desc
2082 return defaultmsg
2073 return defaultmsg
2083
2074
2084 # i18n: this message is shown in editor with "HG: " prefix
2075 # i18n: this message is shown in editor with "HG: " prefix
2085 extramsg = _(b'Leave message empty to use default message.')
2076 extramsg = _(b'Leave message empty to use default message.')
2086 editor = cmdutil.getcommiteditor(
2077 editor = cmdutil.getcommiteditor(
2087 finishdesc=finishdesc,
2078 finishdesc=finishdesc,
2088 extramsg=extramsg,
2079 extramsg=extramsg,
2089 editform=editform,
2080 editform=editform,
2090 )
2081 )
2091 message = msg or b"\n".join(ph.message)
2082 message = msg or b"\n".join(ph.message)
2092 elif not msg:
2083 elif not msg:
2093 if not ph.message:
2084 if not ph.message:
2094 message = defaultmsg
2085 message = defaultmsg
2095 else:
2086 else:
2096 message = b"\n".join(ph.message)
2087 message = b"\n".join(ph.message)
2097 else:
2088 else:
2098 message = msg
2089 message = msg
2099 ph.setmessage(msg)
2090 ph.setmessage(msg)
2100
2091
2101 # Ensure we create a new changeset in the same phase than
2092 # Ensure we create a new changeset in the same phase than
2102 # the old one.
2093 # the old one.
2103 lock = tr = None
2094 lock = tr = None
2104 try:
2095 try:
2105 lock = repo.lock()
2096 lock = repo.lock()
2106 tr = repo.transaction(b'mq')
2097 tr = repo.transaction(b'mq')
2107 n = newcommit(
2098 n = newcommit(
2108 repo,
2099 repo,
2109 oldphase,
2100 oldphase,
2110 message,
2101 message,
2111 user,
2102 user,
2112 ph.date,
2103 ph.date,
2113 match=match,
2104 match=match,
2114 force=True,
2105 force=True,
2115 editor=editor,
2106 editor=editor,
2116 )
2107 )
2117 # only write patch after a successful commit
2108 # only write patch after a successful commit
2118 c = [list(x) for x in refreshchanges]
2109 c = [list(x) for x in refreshchanges]
2119 if inclsubs:
2110 if inclsubs:
2120 self.putsubstate2changes(substatestate, c)
2111 self.putsubstate2changes(substatestate, c)
2121 chunks = patchmod.diff(
2112 chunks = patchmod.diff(
2122 repo, patchparent, changes=c, opts=diffopts
2113 repo, patchparent, changes=c, opts=diffopts
2123 )
2114 )
2124 comments = bytes(ph)
2115 comments = bytes(ph)
2125 if comments:
2116 if comments:
2126 patchf.write(comments)
2117 patchf.write(comments)
2127 for chunk in chunks:
2118 for chunk in chunks:
2128 patchf.write(chunk)
2119 patchf.write(chunk)
2129 patchf.close()
2120 patchf.close()
2130
2121
2131 marks = repo._bookmarks
2122 marks = repo._bookmarks
2132 marks.applychanges(repo, tr, [(bm, n) for bm in bmlist])
2123 marks.applychanges(repo, tr, [(bm, n) for bm in bmlist])
2133 tr.close()
2124 tr.close()
2134
2125
2135 self.applied.append(statusentry(n, patchfn))
2126 self.applied.append(statusentry(n, patchfn))
2136 finally:
2127 finally:
2137 lockmod.release(tr, lock)
2128 lockmod.release(tr, lock)
2138 except: # re-raises
2129 except: # re-raises
2139 ctx = repo[cparents[0]]
2130 ctx = repo[cparents[0]]
2140 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2131 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2141 self.savedirty()
2132 self.savedirty()
2142 self.ui.warn(
2133 self.ui.warn(
2143 _(
2134 _(
2144 b'qrefresh interrupted while patch was popped! '
2135 b'qrefresh interrupted while patch was popped! '
2145 b'(revert --all, qpush to recover)\n'
2136 b'(revert --all, qpush to recover)\n'
2146 )
2137 )
2147 )
2138 )
2148 raise
2139 raise
2149 finally:
2140 finally:
2150 wlock.release()
2141 wlock.release()
2151 self.removeundo(repo)
2142 self.removeundo(repo)
2152
2143
2153 def init(self, repo, create=False):
2144 def init(self, repo, create=False):
2154 if not create and os.path.isdir(self.path):
2145 if not create and os.path.isdir(self.path):
2155 raise error.Abort(_(b"patch queue directory already exists"))
2146 raise error.Abort(_(b"patch queue directory already exists"))
2156 try:
2147 try:
2157 os.mkdir(self.path)
2148 os.mkdir(self.path)
2158 except OSError as inst:
2149 except OSError as inst:
2159 if inst.errno != errno.EEXIST or not create:
2150 if inst.errno != errno.EEXIST or not create:
2160 raise
2151 raise
2161 if create:
2152 if create:
2162 return self.qrepo(create=True)
2153 return self.qrepo(create=True)
2163
2154
2164 def unapplied(self, repo, patch=None):
2155 def unapplied(self, repo, patch=None):
2165 if patch and patch not in self.series:
2156 if patch and patch not in self.series:
2166 raise error.Abort(_(b"patch %s is not in series file") % patch)
2157 raise error.Abort(_(b"patch %s is not in series file") % patch)
2167 if not patch:
2158 if not patch:
2168 start = self.seriesend()
2159 start = self.seriesend()
2169 else:
2160 else:
2170 start = self.series.index(patch) + 1
2161 start = self.series.index(patch) + 1
2171 unapplied = []
2162 unapplied = []
2172 for i in pycompat.xrange(start, len(self.series)):
2163 for i in pycompat.xrange(start, len(self.series)):
2173 pushable, reason = self.pushable(i)
2164 pushable, reason = self.pushable(i)
2174 if pushable:
2165 if pushable:
2175 unapplied.append((i, self.series[i]))
2166 unapplied.append((i, self.series[i]))
2176 self.explainpushable(i)
2167 self.explainpushable(i)
2177 return unapplied
2168 return unapplied
2178
2169
2179 def qseries(
2170 def qseries(
2180 self,
2171 self,
2181 repo,
2172 repo,
2182 missing=None,
2173 missing=None,
2183 start=0,
2174 start=0,
2184 length=None,
2175 length=None,
2185 status=None,
2176 status=None,
2186 summary=False,
2177 summary=False,
2187 ):
2178 ):
2188 def displayname(pfx, patchname, state):
2179 def displayname(pfx, patchname, state):
2189 if pfx:
2180 if pfx:
2190 self.ui.write(pfx)
2181 self.ui.write(pfx)
2191 if summary:
2182 if summary:
2192 ph = patchheader(self.join(patchname), self.plainmode)
2183 ph = patchheader(self.join(patchname), self.plainmode)
2193 if ph.message:
2184 if ph.message:
2194 msg = ph.message[0]
2185 msg = ph.message[0]
2195 else:
2186 else:
2196 msg = b''
2187 msg = b''
2197
2188
2198 if self.ui.formatted():
2189 if self.ui.formatted():
2199 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
2190 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
2200 if width > 0:
2191 if width > 0:
2201 msg = stringutil.ellipsis(msg, width)
2192 msg = stringutil.ellipsis(msg, width)
2202 else:
2193 else:
2203 msg = b''
2194 msg = b''
2204 self.ui.write(patchname, label=b'qseries.' + state)
2195 self.ui.write(patchname, label=b'qseries.' + state)
2205 self.ui.write(b': ')
2196 self.ui.write(b': ')
2206 self.ui.write(msg, label=b'qseries.message.' + state)
2197 self.ui.write(msg, label=b'qseries.message.' + state)
2207 else:
2198 else:
2208 self.ui.write(patchname, label=b'qseries.' + state)
2199 self.ui.write(patchname, label=b'qseries.' + state)
2209 self.ui.write(b'\n')
2200 self.ui.write(b'\n')
2210
2201
2211 applied = {p.name for p in self.applied}
2202 applied = {p.name for p in self.applied}
2212 if length is None:
2203 if length is None:
2213 length = len(self.series) - start
2204 length = len(self.series) - start
2214 if not missing:
2205 if not missing:
2215 if self.ui.verbose:
2206 if self.ui.verbose:
2216 idxwidth = len(b"%d" % (start + length - 1))
2207 idxwidth = len(b"%d" % (start + length - 1))
2217 for i in pycompat.xrange(start, start + length):
2208 for i in pycompat.xrange(start, start + length):
2218 patch = self.series[i]
2209 patch = self.series[i]
2219 if patch in applied:
2210 if patch in applied:
2220 char, state = b'A', b'applied'
2211 char, state = b'A', b'applied'
2221 elif self.pushable(i)[0]:
2212 elif self.pushable(i)[0]:
2222 char, state = b'U', b'unapplied'
2213 char, state = b'U', b'unapplied'
2223 else:
2214 else:
2224 char, state = b'G', b'guarded'
2215 char, state = b'G', b'guarded'
2225 pfx = b''
2216 pfx = b''
2226 if self.ui.verbose:
2217 if self.ui.verbose:
2227 pfx = b'%*d %s ' % (idxwidth, i, char)
2218 pfx = b'%*d %s ' % (idxwidth, i, char)
2228 elif status and status != char:
2219 elif status and status != char:
2229 continue
2220 continue
2230 displayname(pfx, patch, state)
2221 displayname(pfx, patch, state)
2231 else:
2222 else:
2232 msng_list = []
2223 msng_list = []
2233 for root, dirs, files in os.walk(self.path):
2224 for root, dirs, files in os.walk(self.path):
2234 d = root[len(self.path) + 1 :]
2225 d = root[len(self.path) + 1 :]
2235 for f in files:
2226 for f in files:
2236 fl = os.path.join(d, f)
2227 fl = os.path.join(d, f)
2237 if (
2228 if (
2238 fl not in self.series
2229 fl not in self.series
2239 and fl
2230 and fl
2240 not in (
2231 not in (
2241 self.statuspath,
2232 self.statuspath,
2242 self.seriespath,
2233 self.seriespath,
2243 self.guardspath,
2234 self.guardspath,
2244 )
2235 )
2245 and not fl.startswith(b'.')
2236 and not fl.startswith(b'.')
2246 ):
2237 ):
2247 msng_list.append(fl)
2238 msng_list.append(fl)
2248 for x in sorted(msng_list):
2239 for x in sorted(msng_list):
2249 pfx = self.ui.verbose and b'D ' or b''
2240 pfx = self.ui.verbose and b'D ' or b''
2250 displayname(pfx, x, b'missing')
2241 displayname(pfx, x, b'missing')
2251
2242
2252 def issaveline(self, l):
2243 def issaveline(self, l):
2253 if l.name == b'.hg.patches.save.line':
2244 if l.name == b'.hg.patches.save.line':
2254 return True
2245 return True
2255
2246
2256 def qrepo(self, create=False):
2247 def qrepo(self, create=False):
2257 ui = self.baseui.copy()
2248 ui = self.baseui.copy()
2258 # copy back attributes set by ui.pager()
2249 # copy back attributes set by ui.pager()
2259 if self.ui.pageractive and not ui.pageractive:
2250 if self.ui.pageractive and not ui.pageractive:
2260 ui.pageractive = self.ui.pageractive
2251 ui.pageractive = self.ui.pageractive
2261 # internal config: ui.formatted
2252 # internal config: ui.formatted
2262 ui.setconfig(
2253 ui.setconfig(
2263 b'ui',
2254 b'ui',
2264 b'formatted',
2255 b'formatted',
2265 self.ui.config(b'ui', b'formatted'),
2256 self.ui.config(b'ui', b'formatted'),
2266 b'mqpager',
2257 b'mqpager',
2267 )
2258 )
2268 ui.setconfig(
2259 ui.setconfig(
2269 b'ui',
2260 b'ui',
2270 b'interactive',
2261 b'interactive',
2271 self.ui.config(b'ui', b'interactive'),
2262 self.ui.config(b'ui', b'interactive'),
2272 b'mqpager',
2263 b'mqpager',
2273 )
2264 )
2274 if create or os.path.isdir(self.join(b".hg")):
2265 if create or os.path.isdir(self.join(b".hg")):
2275 return hg.repository(ui, path=self.path, create=create)
2266 return hg.repository(ui, path=self.path, create=create)
2276
2267
2277 def restore(self, repo, rev, delete=None, qupdate=None):
2268 def restore(self, repo, rev, delete=None, qupdate=None):
2278 desc = repo[rev].description().strip()
2269 desc = repo[rev].description().strip()
2279 lines = desc.splitlines()
2270 lines = desc.splitlines()
2280 datastart = None
2271 datastart = None
2281 series = []
2272 series = []
2282 applied = []
2273 applied = []
2283 qpp = None
2274 qpp = None
2284 for i, line in enumerate(lines):
2275 for i, line in enumerate(lines):
2285 if line == b'Patch Data:':
2276 if line == b'Patch Data:':
2286 datastart = i + 1
2277 datastart = i + 1
2287 elif line.startswith(b'Dirstate:'):
2278 elif line.startswith(b'Dirstate:'):
2288 l = line.rstrip()
2279 l = line.rstrip()
2289 l = l[10:].split(b' ')
2280 l = l[10:].split(b' ')
2290 qpp = [bin(x) for x in l]
2281 qpp = [bin(x) for x in l]
2291 elif datastart is not None:
2282 elif datastart is not None:
2292 l = line.rstrip()
2283 l = line.rstrip()
2293 n, name = l.split(b':', 1)
2284 n, name = l.split(b':', 1)
2294 if n:
2285 if n:
2295 applied.append(statusentry(bin(n), name))
2286 applied.append(statusentry(bin(n), name))
2296 else:
2287 else:
2297 series.append(l)
2288 series.append(l)
2298 if datastart is None:
2289 if datastart is None:
2299 self.ui.warn(_(b"no saved patch data found\n"))
2290 self.ui.warn(_(b"no saved patch data found\n"))
2300 return 1
2291 return 1
2301 self.ui.warn(_(b"restoring status: %s\n") % lines[0])
2292 self.ui.warn(_(b"restoring status: %s\n") % lines[0])
2302 self.fullseries = series
2293 self.fullseries = series
2303 self.applied = applied
2294 self.applied = applied
2304 self.parseseries()
2295 self.parseseries()
2305 self.seriesdirty = True
2296 self.seriesdirty = True
2306 self.applieddirty = True
2297 self.applieddirty = True
2307 heads = repo.changelog.heads()
2298 heads = repo.changelog.heads()
2308 if delete:
2299 if delete:
2309 if rev not in heads:
2300 if rev not in heads:
2310 self.ui.warn(_(b"save entry has children, leaving it alone\n"))
2301 self.ui.warn(_(b"save entry has children, leaving it alone\n"))
2311 else:
2302 else:
2312 self.ui.warn(_(b"removing save entry %s\n") % short(rev))
2303 self.ui.warn(_(b"removing save entry %s\n") % short(rev))
2313 pp = repo.dirstate.parents()
2304 pp = repo.dirstate.parents()
2314 if rev in pp:
2305 if rev in pp:
2315 update = True
2306 update = True
2316 else:
2307 else:
2317 update = False
2308 update = False
2318 strip(self.ui, repo, [rev], update=update, backup=False)
2309 strip(self.ui, repo, [rev], update=update, backup=False)
2319 if qpp:
2310 if qpp:
2320 self.ui.warn(
2311 self.ui.warn(
2321 _(b"saved queue repository parents: %s %s\n")
2312 _(b"saved queue repository parents: %s %s\n")
2322 % (short(qpp[0]), short(qpp[1]))
2313 % (short(qpp[0]), short(qpp[1]))
2323 )
2314 )
2324 if qupdate:
2315 if qupdate:
2325 self.ui.status(_(b"updating queue directory\n"))
2316 self.ui.status(_(b"updating queue directory\n"))
2326 r = self.qrepo()
2317 r = self.qrepo()
2327 if not r:
2318 if not r:
2328 self.ui.warn(_(b"unable to load queue repository\n"))
2319 self.ui.warn(_(b"unable to load queue repository\n"))
2329 return 1
2320 return 1
2330 hg.clean(r, qpp[0])
2321 hg.clean(r, qpp[0])
2331
2322
2332 def save(self, repo, msg=None):
2323 def save(self, repo, msg=None):
2333 if not self.applied:
2324 if not self.applied:
2334 self.ui.warn(_(b"save: no patches applied, exiting\n"))
2325 self.ui.warn(_(b"save: no patches applied, exiting\n"))
2335 return 1
2326 return 1
2336 if self.issaveline(self.applied[-1]):
2327 if self.issaveline(self.applied[-1]):
2337 self.ui.warn(_(b"status is already saved\n"))
2328 self.ui.warn(_(b"status is already saved\n"))
2338 return 1
2329 return 1
2339
2330
2340 if not msg:
2331 if not msg:
2341 msg = _(b"hg patches saved state")
2332 msg = _(b"hg patches saved state")
2342 else:
2333 else:
2343 msg = b"hg patches: " + msg.rstrip(b'\r\n')
2334 msg = b"hg patches: " + msg.rstrip(b'\r\n')
2344 r = self.qrepo()
2335 r = self.qrepo()
2345 if r:
2336 if r:
2346 pp = r.dirstate.parents()
2337 pp = r.dirstate.parents()
2347 msg += b"\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
2338 msg += b"\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
2348 msg += b"\n\nPatch Data:\n"
2339 msg += b"\n\nPatch Data:\n"
2349 msg += b''.join(b'%s\n' % x for x in self.applied)
2340 msg += b''.join(b'%s\n' % x for x in self.applied)
2350 msg += b''.join(b':%s\n' % x for x in self.fullseries)
2341 msg += b''.join(b':%s\n' % x for x in self.fullseries)
2351 n = repo.commit(msg, force=True)
2342 n = repo.commit(msg, force=True)
2352 if not n:
2343 if not n:
2353 self.ui.warn(_(b"repo commit failed\n"))
2344 self.ui.warn(_(b"repo commit failed\n"))
2354 return 1
2345 return 1
2355 self.applied.append(statusentry(n, b'.hg.patches.save.line'))
2346 self.applied.append(statusentry(n, b'.hg.patches.save.line'))
2356 self.applieddirty = True
2347 self.applieddirty = True
2357 self.removeundo(repo)
2348 self.removeundo(repo)
2358
2349
2359 def fullseriesend(self):
2350 def fullseriesend(self):
2360 if self.applied:
2351 if self.applied:
2361 p = self.applied[-1].name
2352 p = self.applied[-1].name
2362 end = self.findseries(p)
2353 end = self.findseries(p)
2363 if end is None:
2354 if end is None:
2364 return len(self.fullseries)
2355 return len(self.fullseries)
2365 return end + 1
2356 return end + 1
2366 return 0
2357 return 0
2367
2358
2368 def seriesend(self, all_patches=False):
2359 def seriesend(self, all_patches=False):
2369 """If all_patches is False, return the index of the next pushable patch
2360 """If all_patches is False, return the index of the next pushable patch
2370 in the series, or the series length. If all_patches is True, return the
2361 in the series, or the series length. If all_patches is True, return the
2371 index of the first patch past the last applied one.
2362 index of the first patch past the last applied one.
2372 """
2363 """
2373 end = 0
2364 end = 0
2374
2365
2375 def nextpatch(start):
2366 def nextpatch(start):
2376 if all_patches or start >= len(self.series):
2367 if all_patches or start >= len(self.series):
2377 return start
2368 return start
2378 for i in pycompat.xrange(start, len(self.series)):
2369 for i in pycompat.xrange(start, len(self.series)):
2379 p, reason = self.pushable(i)
2370 p, reason = self.pushable(i)
2380 if p:
2371 if p:
2381 return i
2372 return i
2382 self.explainpushable(i)
2373 self.explainpushable(i)
2383 return len(self.series)
2374 return len(self.series)
2384
2375
2385 if self.applied:
2376 if self.applied:
2386 p = self.applied[-1].name
2377 p = self.applied[-1].name
2387 try:
2378 try:
2388 end = self.series.index(p)
2379 end = self.series.index(p)
2389 except ValueError:
2380 except ValueError:
2390 return 0
2381 return 0
2391 return nextpatch(end + 1)
2382 return nextpatch(end + 1)
2392 return nextpatch(end)
2383 return nextpatch(end)
2393
2384
2394 def appliedname(self, index):
2385 def appliedname(self, index):
2395 pname = self.applied[index].name
2386 pname = self.applied[index].name
2396 if not self.ui.verbose:
2387 if not self.ui.verbose:
2397 p = pname
2388 p = pname
2398 else:
2389 else:
2399 p = (b"%d" % self.series.index(pname)) + b" " + pname
2390 p = (b"%d" % self.series.index(pname)) + b" " + pname
2400 return p
2391 return p
2401
2392
2402 def qimport(
2393 def qimport(
2403 self,
2394 self,
2404 repo,
2395 repo,
2405 files,
2396 files,
2406 patchname=None,
2397 patchname=None,
2407 rev=None,
2398 rev=None,
2408 existing=None,
2399 existing=None,
2409 force=None,
2400 force=None,
2410 git=False,
2401 git=False,
2411 ):
2402 ):
2412 def checkseries(patchname):
2403 def checkseries(patchname):
2413 if patchname in self.series:
2404 if patchname in self.series:
2414 raise error.Abort(
2405 raise error.Abort(
2415 _(b'patch %s is already in the series file') % patchname
2406 _(b'patch %s is already in the series file') % patchname
2416 )
2407 )
2417
2408
2418 if rev:
2409 if rev:
2419 if files:
2410 if files:
2420 raise error.Abort(
2411 raise error.Abort(
2421 _(b'option "-r" not valid when importing files')
2412 _(b'option "-r" not valid when importing files')
2422 )
2413 )
2423 rev = scmutil.revrange(repo, rev)
2414 rev = scmutil.revrange(repo, rev)
2424 rev.sort(reverse=True)
2415 rev.sort(reverse=True)
2425 elif not files:
2416 elif not files:
2426 raise error.Abort(_(b'no files or revisions specified'))
2417 raise error.Abort(_(b'no files or revisions specified'))
2427 if (len(files) > 1 or len(rev) > 1) and patchname:
2418 if (len(files) > 1 or len(rev) > 1) and patchname:
2428 raise error.Abort(
2419 raise error.Abort(
2429 _(b'option "-n" not valid when importing multiple patches')
2420 _(b'option "-n" not valid when importing multiple patches')
2430 )
2421 )
2431 imported = []
2422 imported = []
2432 if rev:
2423 if rev:
2433 # If mq patches are applied, we can only import revisions
2424 # If mq patches are applied, we can only import revisions
2434 # that form a linear path to qbase.
2425 # that form a linear path to qbase.
2435 # Otherwise, they should form a linear path to a head.
2426 # Otherwise, they should form a linear path to a head.
2436 heads = repo.changelog.heads(repo.changelog.node(rev.first()))
2427 heads = repo.changelog.heads(repo.changelog.node(rev.first()))
2437 if len(heads) > 1:
2428 if len(heads) > 1:
2438 raise error.Abort(
2429 raise error.Abort(
2439 _(b'revision %d is the root of more than one branch')
2430 _(b'revision %d is the root of more than one branch')
2440 % rev.last()
2431 % rev.last()
2441 )
2432 )
2442 if self.applied:
2433 if self.applied:
2443 base = repo.changelog.node(rev.first())
2434 base = repo.changelog.node(rev.first())
2444 if base in [n.node for n in self.applied]:
2435 if base in [n.node for n in self.applied]:
2445 raise error.Abort(
2436 raise error.Abort(
2446 _(b'revision %d is already managed') % rev.first()
2437 _(b'revision %d is already managed') % rev.first()
2447 )
2438 )
2448 if heads != [self.applied[-1].node]:
2439 if heads != [self.applied[-1].node]:
2449 raise error.Abort(
2440 raise error.Abort(
2450 _(b'revision %d is not the parent of the queue')
2441 _(b'revision %d is not the parent of the queue')
2451 % rev.first()
2442 % rev.first()
2452 )
2443 )
2453 base = repo.changelog.rev(self.applied[0].node)
2444 base = repo.changelog.rev(self.applied[0].node)
2454 lastparent = repo.changelog.parentrevs(base)[0]
2445 lastparent = repo.changelog.parentrevs(base)[0]
2455 else:
2446 else:
2456 if heads != [repo.changelog.node(rev.first())]:
2447 if heads != [repo.changelog.node(rev.first())]:
2457 raise error.Abort(
2448 raise error.Abort(
2458 _(b'revision %d has unmanaged children') % rev.first()
2449 _(b'revision %d has unmanaged children') % rev.first()
2459 )
2450 )
2460 lastparent = None
2451 lastparent = None
2461
2452
2462 diffopts = self.diffopts({b'git': git})
2453 diffopts = self.diffopts({b'git': git})
2463 with repo.transaction(b'qimport') as tr:
2454 with repo.transaction(b'qimport') as tr:
2464 for r in rev:
2455 for r in rev:
2465 if not repo[r].mutable():
2456 if not repo[r].mutable():
2466 raise error.Abort(
2457 raise error.Abort(
2467 _(b'revision %d is not mutable') % r,
2458 _(b'revision %d is not mutable') % r,
2468 hint=_(b"see 'hg help phases' " b'for details'),
2459 hint=_(b"see 'hg help phases' " b'for details'),
2469 )
2460 )
2470 p1, p2 = repo.changelog.parentrevs(r)
2461 p1, p2 = repo.changelog.parentrevs(r)
2471 n = repo.changelog.node(r)
2462 n = repo.changelog.node(r)
2472 if p2 != nullrev:
2463 if p2 != nullrev:
2473 raise error.Abort(
2464 raise error.Abort(
2474 _(b'cannot import merge revision %d') % r
2465 _(b'cannot import merge revision %d') % r
2475 )
2466 )
2476 if lastparent and lastparent != r:
2467 if lastparent and lastparent != r:
2477 raise error.Abort(
2468 raise error.Abort(
2478 _(b'revision %d is not the parent of %d')
2469 _(b'revision %d is not the parent of %d')
2479 % (r, lastparent)
2470 % (r, lastparent)
2480 )
2471 )
2481 lastparent = p1
2472 lastparent = p1
2482
2473
2483 if not patchname:
2474 if not patchname:
2484 patchname = self.makepatchname(
2475 patchname = self.makepatchname(
2485 repo[r].description().split(b'\n', 1)[0],
2476 repo[r].description().split(b'\n', 1)[0],
2486 b'%d.diff' % r,
2477 b'%d.diff' % r,
2487 )
2478 )
2488 checkseries(patchname)
2479 checkseries(patchname)
2489 self.checkpatchname(patchname, force)
2480 self.checkpatchname(patchname, force)
2490 self.fullseries.insert(0, patchname)
2481 self.fullseries.insert(0, patchname)
2491
2482
2492 with self.opener(patchname, b"w") as fp:
2483 with self.opener(patchname, b"w") as fp:
2493 cmdutil.exportfile(repo, [n], fp, opts=diffopts)
2484 cmdutil.exportfile(repo, [n], fp, opts=diffopts)
2494
2485
2495 se = statusentry(n, patchname)
2486 se = statusentry(n, patchname)
2496 self.applied.insert(0, se)
2487 self.applied.insert(0, se)
2497
2488
2498 self.added.append(patchname)
2489 self.added.append(patchname)
2499 imported.append(patchname)
2490 imported.append(patchname)
2500 patchname = None
2491 patchname = None
2501 if rev and repo.ui.configbool(b'mq', b'secret'):
2492 if rev and repo.ui.configbool(b'mq', b'secret'):
2502 # if we added anything with --rev, move the secret root
2493 # if we added anything with --rev, move the secret root
2503 phases.retractboundary(repo, tr, phases.secret, [n])
2494 phases.retractboundary(repo, tr, phases.secret, [n])
2504 self.parseseries()
2495 self.parseseries()
2505 self.applieddirty = True
2496 self.applieddirty = True
2506 self.seriesdirty = True
2497 self.seriesdirty = True
2507
2498
2508 for i, filename in enumerate(files):
2499 for i, filename in enumerate(files):
2509 if existing:
2500 if existing:
2510 if filename == b'-':
2501 if filename == b'-':
2511 raise error.Abort(
2502 raise error.Abort(
2512 _(b'-e is incompatible with import from -')
2503 _(b'-e is incompatible with import from -')
2513 )
2504 )
2514 filename = normname(filename)
2505 filename = normname(filename)
2515 self.checkreservedname(filename)
2506 self.checkreservedname(filename)
2516 if urlutil.url(filename).islocal():
2507 if urlutil.url(filename).islocal():
2517 originpath = self.join(filename)
2508 originpath = self.join(filename)
2518 if not os.path.isfile(originpath):
2509 if not os.path.isfile(originpath):
2519 raise error.Abort(
2510 raise error.Abort(
2520 _(b"patch %s does not exist") % filename
2511 _(b"patch %s does not exist") % filename
2521 )
2512 )
2522
2513
2523 if patchname:
2514 if patchname:
2524 self.checkpatchname(patchname, force)
2515 self.checkpatchname(patchname, force)
2525
2516
2526 self.ui.write(
2517 self.ui.write(
2527 _(b'renaming %s to %s\n') % (filename, patchname)
2518 _(b'renaming %s to %s\n') % (filename, patchname)
2528 )
2519 )
2529 util.rename(originpath, self.join(patchname))
2520 util.rename(originpath, self.join(patchname))
2530 else:
2521 else:
2531 patchname = filename
2522 patchname = filename
2532
2523
2533 else:
2524 else:
2534 if filename == b'-' and not patchname:
2525 if filename == b'-' and not patchname:
2535 raise error.Abort(
2526 raise error.Abort(
2536 _(b'need --name to import a patch from -')
2527 _(b'need --name to import a patch from -')
2537 )
2528 )
2538 elif not patchname:
2529 elif not patchname:
2539 patchname = normname(
2530 patchname = normname(
2540 os.path.basename(filename.rstrip(b'/'))
2531 os.path.basename(filename.rstrip(b'/'))
2541 )
2532 )
2542 self.checkpatchname(patchname, force)
2533 self.checkpatchname(patchname, force)
2543 try:
2534 try:
2544 if filename == b'-':
2535 if filename == b'-':
2545 text = self.ui.fin.read()
2536 text = self.ui.fin.read()
2546 else:
2537 else:
2547 fp = hg.openpath(self.ui, filename)
2538 fp = hg.openpath(self.ui, filename)
2548 text = fp.read()
2539 text = fp.read()
2549 fp.close()
2540 fp.close()
2550 except (OSError, IOError):
2541 except (OSError, IOError):
2551 raise error.Abort(_(b"unable to read file %s") % filename)
2542 raise error.Abort(_(b"unable to read file %s") % filename)
2552 patchf = self.opener(patchname, b"w")
2543 patchf = self.opener(patchname, b"w")
2553 patchf.write(text)
2544 patchf.write(text)
2554 patchf.close()
2545 patchf.close()
2555 if not force:
2546 if not force:
2556 checkseries(patchname)
2547 checkseries(patchname)
2557 if patchname not in self.series:
2548 if patchname not in self.series:
2558 index = self.fullseriesend() + i
2549 index = self.fullseriesend() + i
2559 self.fullseries[index:index] = [patchname]
2550 self.fullseries[index:index] = [patchname]
2560 self.parseseries()
2551 self.parseseries()
2561 self.seriesdirty = True
2552 self.seriesdirty = True
2562 self.ui.warn(_(b"adding %s to series file\n") % patchname)
2553 self.ui.warn(_(b"adding %s to series file\n") % patchname)
2563 self.added.append(patchname)
2554 self.added.append(patchname)
2564 imported.append(patchname)
2555 imported.append(patchname)
2565 patchname = None
2556 patchname = None
2566
2557
2567 self.removeundo(repo)
2558 self.removeundo(repo)
2568 return imported
2559 return imported
2569
2560
2570
2561
2571 def fixkeepchangesopts(ui, opts):
2562 def fixkeepchangesopts(ui, opts):
2572 if (
2563 if (
2573 not ui.configbool(b'mq', b'keepchanges')
2564 not ui.configbool(b'mq', b'keepchanges')
2574 or opts.get(b'force')
2565 or opts.get(b'force')
2575 or opts.get(b'exact')
2566 or opts.get(b'exact')
2576 ):
2567 ):
2577 return opts
2568 return opts
2578 opts = dict(opts)
2569 opts = dict(opts)
2579 opts[b'keep_changes'] = True
2570 opts[b'keep_changes'] = True
2580 return opts
2571 return opts
2581
2572
2582
2573
2583 @command(
2574 @command(
2584 b"qdelete|qremove|qrm",
2575 b"qdelete|qremove|qrm",
2585 [
2576 [
2586 (b'k', b'keep', None, _(b'keep patch file')),
2577 (b'k', b'keep', None, _(b'keep patch file')),
2587 (
2578 (
2588 b'r',
2579 b'r',
2589 b'rev',
2580 b'rev',
2590 [],
2581 [],
2591 _(b'stop managing a revision (DEPRECATED)'),
2582 _(b'stop managing a revision (DEPRECATED)'),
2592 _(b'REV'),
2583 _(b'REV'),
2593 ),
2584 ),
2594 ],
2585 ],
2595 _(b'hg qdelete [-k] [PATCH]...'),
2586 _(b'hg qdelete [-k] [PATCH]...'),
2596 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2587 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2597 )
2588 )
2598 def delete(ui, repo, *patches, **opts):
2589 def delete(ui, repo, *patches, **opts):
2599 """remove patches from queue
2590 """remove patches from queue
2600
2591
2601 The patches must not be applied, and at least one patch is required. Exact
2592 The patches must not be applied, and at least one patch is required. Exact
2602 patch identifiers must be given. With -k/--keep, the patch files are
2593 patch identifiers must be given. With -k/--keep, the patch files are
2603 preserved in the patch directory.
2594 preserved in the patch directory.
2604
2595
2605 To stop managing a patch and move it into permanent history,
2596 To stop managing a patch and move it into permanent history,
2606 use the :hg:`qfinish` command."""
2597 use the :hg:`qfinish` command."""
2607 q = repo.mq
2598 q = repo.mq
2608 q.delete(repo, patches, pycompat.byteskwargs(opts))
2599 q.delete(repo, patches, pycompat.byteskwargs(opts))
2609 q.savedirty()
2600 q.savedirty()
2610 return 0
2601 return 0
2611
2602
2612
2603
2613 @command(
2604 @command(
2614 b"qapplied",
2605 b"qapplied",
2615 [(b'1', b'last', None, _(b'show only the preceding applied patch'))]
2606 [(b'1', b'last', None, _(b'show only the preceding applied patch'))]
2616 + seriesopts,
2607 + seriesopts,
2617 _(b'hg qapplied [-1] [-s] [PATCH]'),
2608 _(b'hg qapplied [-1] [-s] [PATCH]'),
2618 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2609 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2619 )
2610 )
2620 def applied(ui, repo, patch=None, **opts):
2611 def applied(ui, repo, patch=None, **opts):
2621 """print the patches already applied
2612 """print the patches already applied
2622
2613
2623 Returns 0 on success."""
2614 Returns 0 on success."""
2624
2615
2625 q = repo.mq
2616 q = repo.mq
2626 opts = pycompat.byteskwargs(opts)
2617 opts = pycompat.byteskwargs(opts)
2627
2618
2628 if patch:
2619 if patch:
2629 if patch not in q.series:
2620 if patch not in q.series:
2630 raise error.Abort(_(b"patch %s is not in series file") % patch)
2621 raise error.Abort(_(b"patch %s is not in series file") % patch)
2631 end = q.series.index(patch) + 1
2622 end = q.series.index(patch) + 1
2632 else:
2623 else:
2633 end = q.seriesend(True)
2624 end = q.seriesend(True)
2634
2625
2635 if opts.get(b'last') and not end:
2626 if opts.get(b'last') and not end:
2636 ui.write(_(b"no patches applied\n"))
2627 ui.write(_(b"no patches applied\n"))
2637 return 1
2628 return 1
2638 elif opts.get(b'last') and end == 1:
2629 elif opts.get(b'last') and end == 1:
2639 ui.write(_(b"only one patch applied\n"))
2630 ui.write(_(b"only one patch applied\n"))
2640 return 1
2631 return 1
2641 elif opts.get(b'last'):
2632 elif opts.get(b'last'):
2642 start = end - 2
2633 start = end - 2
2643 end = 1
2634 end = 1
2644 else:
2635 else:
2645 start = 0
2636 start = 0
2646
2637
2647 q.qseries(
2638 q.qseries(
2648 repo, length=end, start=start, status=b'A', summary=opts.get(b'summary')
2639 repo, length=end, start=start, status=b'A', summary=opts.get(b'summary')
2649 )
2640 )
2650
2641
2651
2642
2652 @command(
2643 @command(
2653 b"qunapplied",
2644 b"qunapplied",
2654 [(b'1', b'first', None, _(b'show only the first patch'))] + seriesopts,
2645 [(b'1', b'first', None, _(b'show only the first patch'))] + seriesopts,
2655 _(b'hg qunapplied [-1] [-s] [PATCH]'),
2646 _(b'hg qunapplied [-1] [-s] [PATCH]'),
2656 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2647 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2657 )
2648 )
2658 def unapplied(ui, repo, patch=None, **opts):
2649 def unapplied(ui, repo, patch=None, **opts):
2659 """print the patches not yet applied
2650 """print the patches not yet applied
2660
2651
2661 Returns 0 on success."""
2652 Returns 0 on success."""
2662
2653
2663 q = repo.mq
2654 q = repo.mq
2664 opts = pycompat.byteskwargs(opts)
2655 opts = pycompat.byteskwargs(opts)
2665 if patch:
2656 if patch:
2666 if patch not in q.series:
2657 if patch not in q.series:
2667 raise error.Abort(_(b"patch %s is not in series file") % patch)
2658 raise error.Abort(_(b"patch %s is not in series file") % patch)
2668 start = q.series.index(patch) + 1
2659 start = q.series.index(patch) + 1
2669 else:
2660 else:
2670 start = q.seriesend(True)
2661 start = q.seriesend(True)
2671
2662
2672 if start == len(q.series) and opts.get(b'first'):
2663 if start == len(q.series) and opts.get(b'first'):
2673 ui.write(_(b"all patches applied\n"))
2664 ui.write(_(b"all patches applied\n"))
2674 return 1
2665 return 1
2675
2666
2676 if opts.get(b'first'):
2667 if opts.get(b'first'):
2677 length = 1
2668 length = 1
2678 else:
2669 else:
2679 length = None
2670 length = None
2680 q.qseries(
2671 q.qseries(
2681 repo,
2672 repo,
2682 start=start,
2673 start=start,
2683 length=length,
2674 length=length,
2684 status=b'U',
2675 status=b'U',
2685 summary=opts.get(b'summary'),
2676 summary=opts.get(b'summary'),
2686 )
2677 )
2687
2678
2688
2679
2689 @command(
2680 @command(
2690 b"qimport",
2681 b"qimport",
2691 [
2682 [
2692 (b'e', b'existing', None, _(b'import file in patch directory')),
2683 (b'e', b'existing', None, _(b'import file in patch directory')),
2693 (b'n', b'name', b'', _(b'name of patch file'), _(b'NAME')),
2684 (b'n', b'name', b'', _(b'name of patch file'), _(b'NAME')),
2694 (b'f', b'force', None, _(b'overwrite existing files')),
2685 (b'f', b'force', None, _(b'overwrite existing files')),
2695 (
2686 (
2696 b'r',
2687 b'r',
2697 b'rev',
2688 b'rev',
2698 [],
2689 [],
2699 _(b'place existing revisions under mq control'),
2690 _(b'place existing revisions under mq control'),
2700 _(b'REV'),
2691 _(b'REV'),
2701 ),
2692 ),
2702 (b'g', b'git', None, _(b'use git extended diff format')),
2693 (b'g', b'git', None, _(b'use git extended diff format')),
2703 (b'P', b'push', None, _(b'qpush after importing')),
2694 (b'P', b'push', None, _(b'qpush after importing')),
2704 ],
2695 ],
2705 _(b'hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... [FILE]...'),
2696 _(b'hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... [FILE]...'),
2706 helpcategory=command.CATEGORY_IMPORT_EXPORT,
2697 helpcategory=command.CATEGORY_IMPORT_EXPORT,
2707 )
2698 )
2708 def qimport(ui, repo, *filename, **opts):
2699 def qimport(ui, repo, *filename, **opts):
2709 """import a patch or existing changeset
2700 """import a patch or existing changeset
2710
2701
2711 The patch is inserted into the series after the last applied
2702 The patch is inserted into the series after the last applied
2712 patch. If no patches have been applied, qimport prepends the patch
2703 patch. If no patches have been applied, qimport prepends the patch
2713 to the series.
2704 to the series.
2714
2705
2715 The patch will have the same name as its source file unless you
2706 The patch will have the same name as its source file unless you
2716 give it a new one with -n/--name.
2707 give it a new one with -n/--name.
2717
2708
2718 You can register an existing patch inside the patch directory with
2709 You can register an existing patch inside the patch directory with
2719 the -e/--existing flag.
2710 the -e/--existing flag.
2720
2711
2721 With -f/--force, an existing patch of the same name will be
2712 With -f/--force, an existing patch of the same name will be
2722 overwritten.
2713 overwritten.
2723
2714
2724 An existing changeset may be placed under mq control with -r/--rev
2715 An existing changeset may be placed under mq control with -r/--rev
2725 (e.g. qimport --rev . -n patch will place the current revision
2716 (e.g. qimport --rev . -n patch will place the current revision
2726 under mq control). With -g/--git, patches imported with --rev will
2717 under mq control). With -g/--git, patches imported with --rev will
2727 use the git diff format. See the diffs help topic for information
2718 use the git diff format. See the diffs help topic for information
2728 on why this is important for preserving rename/copy information
2719 on why this is important for preserving rename/copy information
2729 and permission changes. Use :hg:`qfinish` to remove changesets
2720 and permission changes. Use :hg:`qfinish` to remove changesets
2730 from mq control.
2721 from mq control.
2731
2722
2732 To import a patch from standard input, pass - as the patch file.
2723 To import a patch from standard input, pass - as the patch file.
2733 When importing from standard input, a patch name must be specified
2724 When importing from standard input, a patch name must be specified
2734 using the --name flag.
2725 using the --name flag.
2735
2726
2736 To import an existing patch while renaming it::
2727 To import an existing patch while renaming it::
2737
2728
2738 hg qimport -e existing-patch -n new-name
2729 hg qimport -e existing-patch -n new-name
2739
2730
2740 Returns 0 if import succeeded.
2731 Returns 0 if import succeeded.
2741 """
2732 """
2742 opts = pycompat.byteskwargs(opts)
2733 opts = pycompat.byteskwargs(opts)
2743 with repo.lock(): # cause this may move phase
2734 with repo.lock(): # cause this may move phase
2744 q = repo.mq
2735 q = repo.mq
2745 try:
2736 try:
2746 imported = q.qimport(
2737 imported = q.qimport(
2747 repo,
2738 repo,
2748 filename,
2739 filename,
2749 patchname=opts.get(b'name'),
2740 patchname=opts.get(b'name'),
2750 existing=opts.get(b'existing'),
2741 existing=opts.get(b'existing'),
2751 force=opts.get(b'force'),
2742 force=opts.get(b'force'),
2752 rev=opts.get(b'rev'),
2743 rev=opts.get(b'rev'),
2753 git=opts.get(b'git'),
2744 git=opts.get(b'git'),
2754 )
2745 )
2755 finally:
2746 finally:
2756 q.savedirty()
2747 q.savedirty()
2757
2748
2758 if imported and opts.get(b'push') and not opts.get(b'rev'):
2749 if imported and opts.get(b'push') and not opts.get(b'rev'):
2759 return q.push(repo, imported[-1])
2750 return q.push(repo, imported[-1])
2760 return 0
2751 return 0
2761
2752
2762
2753
2763 def qinit(ui, repo, create):
2754 def qinit(ui, repo, create):
2764 """initialize a new queue repository
2755 """initialize a new queue repository
2765
2756
2766 This command also creates a series file for ordering patches, and
2757 This command also creates a series file for ordering patches, and
2767 an mq-specific .hgignore file in the queue repository, to exclude
2758 an mq-specific .hgignore file in the queue repository, to exclude
2768 the status and guards files (these contain mostly transient state).
2759 the status and guards files (these contain mostly transient state).
2769
2760
2770 Returns 0 if initialization succeeded."""
2761 Returns 0 if initialization succeeded."""
2771 q = repo.mq
2762 q = repo.mq
2772 r = q.init(repo, create)
2763 r = q.init(repo, create)
2773 q.savedirty()
2764 q.savedirty()
2774 if r:
2765 if r:
2775 if not os.path.exists(r.wjoin(b'.hgignore')):
2766 if not os.path.exists(r.wjoin(b'.hgignore')):
2776 fp = r.wvfs(b'.hgignore', b'w')
2767 fp = r.wvfs(b'.hgignore', b'w')
2777 fp.write(b'^\\.hg\n')
2768 fp.write(b'^\\.hg\n')
2778 fp.write(b'^\\.mq\n')
2769 fp.write(b'^\\.mq\n')
2779 fp.write(b'syntax: glob\n')
2770 fp.write(b'syntax: glob\n')
2780 fp.write(b'status\n')
2771 fp.write(b'status\n')
2781 fp.write(b'guards\n')
2772 fp.write(b'guards\n')
2782 fp.close()
2773 fp.close()
2783 if not os.path.exists(r.wjoin(b'series')):
2774 if not os.path.exists(r.wjoin(b'series')):
2784 r.wvfs(b'series', b'w').close()
2775 r.wvfs(b'series', b'w').close()
2785 r[None].add([b'.hgignore', b'series'])
2776 r[None].add([b'.hgignore', b'series'])
2786 commands.add(ui, r)
2777 commands.add(ui, r)
2787 return 0
2778 return 0
2788
2779
2789
2780
2790 @command(
2781 @command(
2791 b"qinit",
2782 b"qinit",
2792 [(b'c', b'create-repo', None, _(b'create queue repository'))],
2783 [(b'c', b'create-repo', None, _(b'create queue repository'))],
2793 _(b'hg qinit [-c]'),
2784 _(b'hg qinit [-c]'),
2794 helpcategory=command.CATEGORY_REPO_CREATION,
2785 helpcategory=command.CATEGORY_REPO_CREATION,
2795 helpbasic=True,
2786 helpbasic=True,
2796 )
2787 )
2797 def init(ui, repo, **opts):
2788 def init(ui, repo, **opts):
2798 """init a new queue repository (DEPRECATED)
2789 """init a new queue repository (DEPRECATED)
2799
2790
2800 The queue repository is unversioned by default. If
2791 The queue repository is unversioned by default. If
2801 -c/--create-repo is specified, qinit will create a separate nested
2792 -c/--create-repo is specified, qinit will create a separate nested
2802 repository for patches (qinit -c may also be run later to convert
2793 repository for patches (qinit -c may also be run later to convert
2803 an unversioned patch repository into a versioned one). You can use
2794 an unversioned patch repository into a versioned one). You can use
2804 qcommit to commit changes to this queue repository.
2795 qcommit to commit changes to this queue repository.
2805
2796
2806 This command is deprecated. Without -c, it's implied by other relevant
2797 This command is deprecated. Without -c, it's implied by other relevant
2807 commands. With -c, use :hg:`init --mq` instead."""
2798 commands. With -c, use :hg:`init --mq` instead."""
2808 return qinit(ui, repo, create=opts.get('create_repo'))
2799 return qinit(ui, repo, create=opts.get('create_repo'))
2809
2800
2810
2801
2811 @command(
2802 @command(
2812 b"qclone",
2803 b"qclone",
2813 [
2804 [
2814 (b'', b'pull', None, _(b'use pull protocol to copy metadata')),
2805 (b'', b'pull', None, _(b'use pull protocol to copy metadata')),
2815 (
2806 (
2816 b'U',
2807 b'U',
2817 b'noupdate',
2808 b'noupdate',
2818 None,
2809 None,
2819 _(b'do not update the new working directories'),
2810 _(b'do not update the new working directories'),
2820 ),
2811 ),
2821 (
2812 (
2822 b'',
2813 b'',
2823 b'uncompressed',
2814 b'uncompressed',
2824 None,
2815 None,
2825 _(b'use uncompressed transfer (fast over LAN)'),
2816 _(b'use uncompressed transfer (fast over LAN)'),
2826 ),
2817 ),
2827 (
2818 (
2828 b'p',
2819 b'p',
2829 b'patches',
2820 b'patches',
2830 b'',
2821 b'',
2831 _(b'location of source patch repository'),
2822 _(b'location of source patch repository'),
2832 _(b'REPO'),
2823 _(b'REPO'),
2833 ),
2824 ),
2834 ]
2825 ]
2835 + cmdutil.remoteopts,
2826 + cmdutil.remoteopts,
2836 _(b'hg qclone [OPTION]... SOURCE [DEST]'),
2827 _(b'hg qclone [OPTION]... SOURCE [DEST]'),
2837 helpcategory=command.CATEGORY_REPO_CREATION,
2828 helpcategory=command.CATEGORY_REPO_CREATION,
2838 norepo=True,
2829 norepo=True,
2839 )
2830 )
2840 def clone(ui, source, dest=None, **opts):
2831 def clone(ui, source, dest=None, **opts):
2841 """clone main and patch repository at same time
2832 """clone main and patch repository at same time
2842
2833
2843 If source is local, destination will have no patches applied. If
2834 If source is local, destination will have no patches applied. If
2844 source is remote, this command can not check if patches are
2835 source is remote, this command can not check if patches are
2845 applied in source, so cannot guarantee that patches are not
2836 applied in source, so cannot guarantee that patches are not
2846 applied in destination. If you clone remote repository, be sure
2837 applied in destination. If you clone remote repository, be sure
2847 before that it has no patches applied.
2838 before that it has no patches applied.
2848
2839
2849 Source patch repository is looked for in <src>/.hg/patches by
2840 Source patch repository is looked for in <src>/.hg/patches by
2850 default. Use -p <url> to change.
2841 default. Use -p <url> to change.
2851
2842
2852 The patch directory must be a nested Mercurial repository, as
2843 The patch directory must be a nested Mercurial repository, as
2853 would be created by :hg:`init --mq`.
2844 would be created by :hg:`init --mq`.
2854
2845
2855 Return 0 on success.
2846 Return 0 on success.
2856 """
2847 """
2857 opts = pycompat.byteskwargs(opts)
2848 opts = pycompat.byteskwargs(opts)
2858
2849
2859 def patchdir(repo):
2850 def patchdir(repo):
2860 """compute a patch repo url from a repo object"""
2851 """compute a patch repo url from a repo object"""
2861 url = repo.url()
2852 url = repo.url()
2862 if url.endswith(b'/'):
2853 if url.endswith(b'/'):
2863 url = url[:-1]
2854 url = url[:-1]
2864 return url + b'/.hg/patches'
2855 return url + b'/.hg/patches'
2865
2856
2866 # main repo (destination and sources)
2857 # main repo (destination and sources)
2867 if dest is None:
2858 if dest is None:
2868 dest = hg.defaultdest(source)
2859 dest = hg.defaultdest(source)
2869 __, source_path, __ = urlutil.get_clone_path(ui, source)
2860 __, source_path, __ = urlutil.get_clone_path(ui, source)
2870 sr = hg.peer(ui, opts, source_path)
2861 sr = hg.peer(ui, opts, source_path)
2871
2862
2872 # patches repo (source only)
2863 # patches repo (source only)
2873 if opts.get(b'patches'):
2864 if opts.get(b'patches'):
2874 __, patchespath, __ = urlutil.get_clone_path(ui, opts.get(b'patches'))
2865 __, patchespath, __ = urlutil.get_clone_path(ui, opts.get(b'patches'))
2875 else:
2866 else:
2876 patchespath = patchdir(sr)
2867 patchespath = patchdir(sr)
2877 try:
2868 try:
2878 hg.peer(ui, opts, patchespath)
2869 hg.peer(ui, opts, patchespath)
2879 except error.RepoError:
2870 except error.RepoError:
2880 raise error.Abort(
2871 raise error.Abort(
2881 _(b'versioned patch repository not found (see init --mq)')
2872 _(b'versioned patch repository not found (see init --mq)')
2882 )
2873 )
2883 qbase, destrev = None, None
2874 qbase, destrev = None, None
2884 if sr.local():
2875 if sr.local():
2885 repo = sr.local()
2876 repo = sr.local()
2886 if repo.mq.applied and repo[qbase].phase() != phases.secret:
2877 if repo.mq.applied and repo[qbase].phase() != phases.secret:
2887 qbase = repo.mq.applied[0].node
2878 qbase = repo.mq.applied[0].node
2888 if not hg.islocal(dest):
2879 if not hg.islocal(dest):
2889 heads = set(repo.heads())
2880 heads = set(repo.heads())
2890 destrev = list(heads.difference(repo.heads(qbase)))
2881 destrev = list(heads.difference(repo.heads(qbase)))
2891 destrev.append(repo.changelog.parents(qbase)[0])
2882 destrev.append(repo.changelog.parents(qbase)[0])
2892 elif sr.capable(b'lookup'):
2883 elif sr.capable(b'lookup'):
2893 try:
2884 try:
2894 qbase = sr.lookup(b'qbase')
2885 qbase = sr.lookup(b'qbase')
2895 except error.RepoError:
2886 except error.RepoError:
2896 pass
2887 pass
2897
2888
2898 ui.note(_(b'cloning main repository\n'))
2889 ui.note(_(b'cloning main repository\n'))
2899 sr, dr = hg.clone(
2890 sr, dr = hg.clone(
2900 ui,
2891 ui,
2901 opts,
2892 opts,
2902 sr.url(),
2893 sr.url(),
2903 dest,
2894 dest,
2904 pull=opts.get(b'pull'),
2895 pull=opts.get(b'pull'),
2905 revs=destrev,
2896 revs=destrev,
2906 update=False,
2897 update=False,
2907 stream=opts.get(b'uncompressed'),
2898 stream=opts.get(b'uncompressed'),
2908 )
2899 )
2909
2900
2910 ui.note(_(b'cloning patch repository\n'))
2901 ui.note(_(b'cloning patch repository\n'))
2911 hg.clone(
2902 hg.clone(
2912 ui,
2903 ui,
2913 opts,
2904 opts,
2914 opts.get(b'patches') or patchdir(sr),
2905 opts.get(b'patches') or patchdir(sr),
2915 patchdir(dr),
2906 patchdir(dr),
2916 pull=opts.get(b'pull'),
2907 pull=opts.get(b'pull'),
2917 update=not opts.get(b'noupdate'),
2908 update=not opts.get(b'noupdate'),
2918 stream=opts.get(b'uncompressed'),
2909 stream=opts.get(b'uncompressed'),
2919 )
2910 )
2920
2911
2921 if dr.local():
2912 if dr.local():
2922 repo = dr.local()
2913 repo = dr.local()
2923 if qbase:
2914 if qbase:
2924 ui.note(
2915 ui.note(
2925 _(
2916 _(
2926 b'stripping applied patches from destination '
2917 b'stripping applied patches from destination '
2927 b'repository\n'
2918 b'repository\n'
2928 )
2919 )
2929 )
2920 )
2930 strip(ui, repo, [qbase], update=False, backup=None)
2921 strip(ui, repo, [qbase], update=False, backup=None)
2931 if not opts.get(b'noupdate'):
2922 if not opts.get(b'noupdate'):
2932 ui.note(_(b'updating destination repository\n'))
2923 ui.note(_(b'updating destination repository\n'))
2933 hg.update(repo, repo.changelog.tip())
2924 hg.update(repo, repo.changelog.tip())
2934
2925
2935
2926
2936 @command(
2927 @command(
2937 b"qcommit|qci",
2928 b"qcommit|qci",
2938 commands.table[b"commit|ci"][1],
2929 commands.table[b"commit|ci"][1],
2939 _(b'hg qcommit [OPTION]... [FILE]...'),
2930 _(b'hg qcommit [OPTION]... [FILE]...'),
2940 helpcategory=command.CATEGORY_COMMITTING,
2931 helpcategory=command.CATEGORY_COMMITTING,
2941 inferrepo=True,
2932 inferrepo=True,
2942 )
2933 )
2943 def commit(ui, repo, *pats, **opts):
2934 def commit(ui, repo, *pats, **opts):
2944 """commit changes in the queue repository (DEPRECATED)
2935 """commit changes in the queue repository (DEPRECATED)
2945
2936
2946 This command is deprecated; use :hg:`commit --mq` instead."""
2937 This command is deprecated; use :hg:`commit --mq` instead."""
2947 q = repo.mq
2938 q = repo.mq
2948 r = q.qrepo()
2939 r = q.qrepo()
2949 if not r:
2940 if not r:
2950 raise error.Abort(b'no queue repository')
2941 raise error.Abort(b'no queue repository')
2951 commands.commit(r.ui, r, *pats, **opts)
2942 commands.commit(r.ui, r, *pats, **opts)
2952
2943
2953
2944
2954 @command(
2945 @command(
2955 b"qseries",
2946 b"qseries",
2956 [
2947 [
2957 (b'm', b'missing', None, _(b'print patches not in series')),
2948 (b'm', b'missing', None, _(b'print patches not in series')),
2958 ]
2949 ]
2959 + seriesopts,
2950 + seriesopts,
2960 _(b'hg qseries [-ms]'),
2951 _(b'hg qseries [-ms]'),
2961 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2952 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2962 )
2953 )
2963 def series(ui, repo, **opts):
2954 def series(ui, repo, **opts):
2964 """print the entire series file
2955 """print the entire series file
2965
2956
2966 Returns 0 on success."""
2957 Returns 0 on success."""
2967 repo.mq.qseries(
2958 repo.mq.qseries(
2968 repo, missing=opts.get('missing'), summary=opts.get('summary')
2959 repo, missing=opts.get('missing'), summary=opts.get('summary')
2969 )
2960 )
2970 return 0
2961 return 0
2971
2962
2972
2963
2973 @command(
2964 @command(
2974 b"qtop",
2965 b"qtop",
2975 seriesopts,
2966 seriesopts,
2976 _(b'hg qtop [-s]'),
2967 _(b'hg qtop [-s]'),
2977 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2968 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2978 )
2969 )
2979 def top(ui, repo, **opts):
2970 def top(ui, repo, **opts):
2980 """print the name of the current patch
2971 """print the name of the current patch
2981
2972
2982 Returns 0 on success."""
2973 Returns 0 on success."""
2983 q = repo.mq
2974 q = repo.mq
2984 if q.applied:
2975 if q.applied:
2985 t = q.seriesend(True)
2976 t = q.seriesend(True)
2986 else:
2977 else:
2987 t = 0
2978 t = 0
2988
2979
2989 if t:
2980 if t:
2990 q.qseries(
2981 q.qseries(
2991 repo,
2982 repo,
2992 start=t - 1,
2983 start=t - 1,
2993 length=1,
2984 length=1,
2994 status=b'A',
2985 status=b'A',
2995 summary=opts.get('summary'),
2986 summary=opts.get('summary'),
2996 )
2987 )
2997 else:
2988 else:
2998 ui.write(_(b"no patches applied\n"))
2989 ui.write(_(b"no patches applied\n"))
2999 return 1
2990 return 1
3000
2991
3001
2992
3002 @command(
2993 @command(
3003 b"qnext",
2994 b"qnext",
3004 seriesopts,
2995 seriesopts,
3005 _(b'hg qnext [-s]'),
2996 _(b'hg qnext [-s]'),
3006 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2997 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3007 )
2998 )
3008 def next(ui, repo, **opts):
2999 def next(ui, repo, **opts):
3009 """print the name of the next pushable patch
3000 """print the name of the next pushable patch
3010
3001
3011 Returns 0 on success."""
3002 Returns 0 on success."""
3012 q = repo.mq
3003 q = repo.mq
3013 end = q.seriesend()
3004 end = q.seriesend()
3014 if end == len(q.series):
3005 if end == len(q.series):
3015 ui.write(_(b"all patches applied\n"))
3006 ui.write(_(b"all patches applied\n"))
3016 return 1
3007 return 1
3017 q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
3008 q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
3018
3009
3019
3010
3020 @command(
3011 @command(
3021 b"qprev",
3012 b"qprev",
3022 seriesopts,
3013 seriesopts,
3023 _(b'hg qprev [-s]'),
3014 _(b'hg qprev [-s]'),
3024 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3015 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3025 )
3016 )
3026 def prev(ui, repo, **opts):
3017 def prev(ui, repo, **opts):
3027 """print the name of the preceding applied patch
3018 """print the name of the preceding applied patch
3028
3019
3029 Returns 0 on success."""
3020 Returns 0 on success."""
3030 q = repo.mq
3021 q = repo.mq
3031 l = len(q.applied)
3022 l = len(q.applied)
3032 if l == 1:
3023 if l == 1:
3033 ui.write(_(b"only one patch applied\n"))
3024 ui.write(_(b"only one patch applied\n"))
3034 return 1
3025 return 1
3035 if not l:
3026 if not l:
3036 ui.write(_(b"no patches applied\n"))
3027 ui.write(_(b"no patches applied\n"))
3037 return 1
3028 return 1
3038 idx = q.series.index(q.applied[-2].name)
3029 idx = q.series.index(q.applied[-2].name)
3039 q.qseries(
3030 q.qseries(
3040 repo, start=idx, length=1, status=b'A', summary=opts.get('summary')
3031 repo, start=idx, length=1, status=b'A', summary=opts.get('summary')
3041 )
3032 )
3042
3033
3043
3034
3044 def setupheaderopts(ui, opts):
3035 def setupheaderopts(ui, opts):
3045 if not opts.get(b'user') and opts.get(b'currentuser'):
3036 if not opts.get(b'user') and opts.get(b'currentuser'):
3046 opts[b'user'] = ui.username()
3037 opts[b'user'] = ui.username()
3047 if not opts.get(b'date') and opts.get(b'currentdate'):
3038 if not opts.get(b'date') and opts.get(b'currentdate'):
3048 opts[b'date'] = b"%d %d" % dateutil.makedate()
3039 opts[b'date'] = b"%d %d" % dateutil.makedate()
3049
3040
3050
3041
3051 @command(
3042 @command(
3052 b"qnew",
3043 b"qnew",
3053 [
3044 [
3054 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
3045 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
3055 (b'f', b'force', None, _(b'import uncommitted changes (DEPRECATED)')),
3046 (b'f', b'force', None, _(b'import uncommitted changes (DEPRECATED)')),
3056 (b'g', b'git', None, _(b'use git extended diff format')),
3047 (b'g', b'git', None, _(b'use git extended diff format')),
3057 (b'U', b'currentuser', None, _(b'add "From: <current user>" to patch')),
3048 (b'U', b'currentuser', None, _(b'add "From: <current user>" to patch')),
3058 (b'u', b'user', b'', _(b'add "From: <USER>" to patch'), _(b'USER')),
3049 (b'u', b'user', b'', _(b'add "From: <USER>" to patch'), _(b'USER')),
3059 (b'D', b'currentdate', None, _(b'add "Date: <current date>" to patch')),
3050 (b'D', b'currentdate', None, _(b'add "Date: <current date>" to patch')),
3060 (b'd', b'date', b'', _(b'add "Date: <DATE>" to patch'), _(b'DATE')),
3051 (b'd', b'date', b'', _(b'add "Date: <DATE>" to patch'), _(b'DATE')),
3061 ]
3052 ]
3062 + cmdutil.walkopts
3053 + cmdutil.walkopts
3063 + cmdutil.commitopts,
3054 + cmdutil.commitopts,
3064 _(b'hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'),
3055 _(b'hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'),
3065 helpcategory=command.CATEGORY_COMMITTING,
3056 helpcategory=command.CATEGORY_COMMITTING,
3066 helpbasic=True,
3057 helpbasic=True,
3067 inferrepo=True,
3058 inferrepo=True,
3068 )
3059 )
3069 def new(ui, repo, patch, *args, **opts):
3060 def new(ui, repo, patch, *args, **opts):
3070 """create a new patch
3061 """create a new patch
3071
3062
3072 qnew creates a new patch on top of the currently-applied patch (if
3063 qnew creates a new patch on top of the currently-applied patch (if
3073 any). The patch will be initialized with any outstanding changes
3064 any). The patch will be initialized with any outstanding changes
3074 in the working directory. You may also use -I/--include,
3065 in the working directory. You may also use -I/--include,
3075 -X/--exclude, and/or a list of files after the patch name to add
3066 -X/--exclude, and/or a list of files after the patch name to add
3076 only changes to matching files to the new patch, leaving the rest
3067 only changes to matching files to the new patch, leaving the rest
3077 as uncommitted modifications.
3068 as uncommitted modifications.
3078
3069
3079 -u/--user and -d/--date can be used to set the (given) user and
3070 -u/--user and -d/--date can be used to set the (given) user and
3080 date, respectively. -U/--currentuser and -D/--currentdate set user
3071 date, respectively. -U/--currentuser and -D/--currentdate set user
3081 to current user and date to current date.
3072 to current user and date to current date.
3082
3073
3083 -e/--edit, -m/--message or -l/--logfile set the patch header as
3074 -e/--edit, -m/--message or -l/--logfile set the patch header as
3084 well as the commit message. If none is specified, the header is
3075 well as the commit message. If none is specified, the header is
3085 empty and the commit message is '[mq]: PATCH'.
3076 empty and the commit message is '[mq]: PATCH'.
3086
3077
3087 Use the -g/--git option to keep the patch in the git extended diff
3078 Use the -g/--git option to keep the patch in the git extended diff
3088 format. Read the diffs help topic for more information on why this
3079 format. Read the diffs help topic for more information on why this
3089 is important for preserving permission changes and copy/rename
3080 is important for preserving permission changes and copy/rename
3090 information.
3081 information.
3091
3082
3092 Returns 0 on successful creation of a new patch.
3083 Returns 0 on successful creation of a new patch.
3093 """
3084 """
3094 opts = pycompat.byteskwargs(opts)
3085 opts = pycompat.byteskwargs(opts)
3095 msg = cmdutil.logmessage(ui, opts)
3086 msg = cmdutil.logmessage(ui, opts)
3096 q = repo.mq
3087 q = repo.mq
3097 opts[b'msg'] = msg
3088 opts[b'msg'] = msg
3098 setupheaderopts(ui, opts)
3089 setupheaderopts(ui, opts)
3099 q.new(repo, patch, *args, **pycompat.strkwargs(opts))
3090 q.new(repo, patch, *args, **pycompat.strkwargs(opts))
3100 q.savedirty()
3091 q.savedirty()
3101 return 0
3092 return 0
3102
3093
3103
3094
3104 @command(
3095 @command(
3105 b"qrefresh",
3096 b"qrefresh",
3106 [
3097 [
3107 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
3098 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
3108 (b'g', b'git', None, _(b'use git extended diff format')),
3099 (b'g', b'git', None, _(b'use git extended diff format')),
3109 (
3100 (
3110 b's',
3101 b's',
3111 b'short',
3102 b'short',
3112 None,
3103 None,
3113 _(b'refresh only files already in the patch and specified files'),
3104 _(b'refresh only files already in the patch and specified files'),
3114 ),
3105 ),
3115 (
3106 (
3116 b'U',
3107 b'U',
3117 b'currentuser',
3108 b'currentuser',
3118 None,
3109 None,
3119 _(b'add/update author field in patch with current user'),
3110 _(b'add/update author field in patch with current user'),
3120 ),
3111 ),
3121 (
3112 (
3122 b'u',
3113 b'u',
3123 b'user',
3114 b'user',
3124 b'',
3115 b'',
3125 _(b'add/update author field in patch with given user'),
3116 _(b'add/update author field in patch with given user'),
3126 _(b'USER'),
3117 _(b'USER'),
3127 ),
3118 ),
3128 (
3119 (
3129 b'D',
3120 b'D',
3130 b'currentdate',
3121 b'currentdate',
3131 None,
3122 None,
3132 _(b'add/update date field in patch with current date'),
3123 _(b'add/update date field in patch with current date'),
3133 ),
3124 ),
3134 (
3125 (
3135 b'd',
3126 b'd',
3136 b'date',
3127 b'date',
3137 b'',
3128 b'',
3138 _(b'add/update date field in patch with given date'),
3129 _(b'add/update date field in patch with given date'),
3139 _(b'DATE'),
3130 _(b'DATE'),
3140 ),
3131 ),
3141 ]
3132 ]
3142 + cmdutil.walkopts
3133 + cmdutil.walkopts
3143 + cmdutil.commitopts,
3134 + cmdutil.commitopts,
3144 _(b'hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'),
3135 _(b'hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'),
3145 helpcategory=command.CATEGORY_COMMITTING,
3136 helpcategory=command.CATEGORY_COMMITTING,
3146 helpbasic=True,
3137 helpbasic=True,
3147 inferrepo=True,
3138 inferrepo=True,
3148 )
3139 )
3149 def refresh(ui, repo, *pats, **opts):
3140 def refresh(ui, repo, *pats, **opts):
3150 """update the current patch
3141 """update the current patch
3151
3142
3152 If any file patterns are provided, the refreshed patch will
3143 If any file patterns are provided, the refreshed patch will
3153 contain only the modifications that match those patterns; the
3144 contain only the modifications that match those patterns; the
3154 remaining modifications will remain in the working directory.
3145 remaining modifications will remain in the working directory.
3155
3146
3156 If -s/--short is specified, files currently included in the patch
3147 If -s/--short is specified, files currently included in the patch
3157 will be refreshed just like matched files and remain in the patch.
3148 will be refreshed just like matched files and remain in the patch.
3158
3149
3159 If -e/--edit is specified, Mercurial will start your configured editor for
3150 If -e/--edit is specified, Mercurial will start your configured editor for
3160 you to enter a message. In case qrefresh fails, you will find a backup of
3151 you to enter a message. In case qrefresh fails, you will find a backup of
3161 your message in ``.hg/last-message.txt``.
3152 your message in ``.hg/last-message.txt``.
3162
3153
3163 hg add/remove/copy/rename work as usual, though you might want to
3154 hg add/remove/copy/rename work as usual, though you might want to
3164 use git-style patches (-g/--git or [diff] git=1) to track copies
3155 use git-style patches (-g/--git or [diff] git=1) to track copies
3165 and renames. See the diffs help topic for more information on the
3156 and renames. See the diffs help topic for more information on the
3166 git diff format.
3157 git diff format.
3167
3158
3168 Returns 0 on success.
3159 Returns 0 on success.
3169 """
3160 """
3170 opts = pycompat.byteskwargs(opts)
3161 opts = pycompat.byteskwargs(opts)
3171 q = repo.mq
3162 q = repo.mq
3172 message = cmdutil.logmessage(ui, opts)
3163 message = cmdutil.logmessage(ui, opts)
3173 setupheaderopts(ui, opts)
3164 setupheaderopts(ui, opts)
3174 with repo.wlock():
3165 with repo.wlock():
3175 ret = q.refresh(repo, pats, msg=message, **pycompat.strkwargs(opts))
3166 ret = q.refresh(repo, pats, msg=message, **pycompat.strkwargs(opts))
3176 q.savedirty()
3167 q.savedirty()
3177 return ret
3168 return ret
3178
3169
3179
3170
3180 @command(
3171 @command(
3181 b"qdiff",
3172 b"qdiff",
3182 cmdutil.diffopts + cmdutil.diffopts2 + cmdutil.walkopts,
3173 cmdutil.diffopts + cmdutil.diffopts2 + cmdutil.walkopts,
3183 _(b'hg qdiff [OPTION]... [FILE]...'),
3174 _(b'hg qdiff [OPTION]... [FILE]...'),
3184 helpcategory=command.CATEGORY_FILE_CONTENTS,
3175 helpcategory=command.CATEGORY_FILE_CONTENTS,
3185 helpbasic=True,
3176 helpbasic=True,
3186 inferrepo=True,
3177 inferrepo=True,
3187 )
3178 )
3188 def diff(ui, repo, *pats, **opts):
3179 def diff(ui, repo, *pats, **opts):
3189 """diff of the current patch and subsequent modifications
3180 """diff of the current patch and subsequent modifications
3190
3181
3191 Shows a diff which includes the current patch as well as any
3182 Shows a diff which includes the current patch as well as any
3192 changes which have been made in the working directory since the
3183 changes which have been made in the working directory since the
3193 last refresh (thus showing what the current patch would become
3184 last refresh (thus showing what the current patch would become
3194 after a qrefresh).
3185 after a qrefresh).
3195
3186
3196 Use :hg:`diff` if you only want to see the changes made since the
3187 Use :hg:`diff` if you only want to see the changes made since the
3197 last qrefresh, or :hg:`export qtip` if you want to see changes
3188 last qrefresh, or :hg:`export qtip` if you want to see changes
3198 made by the current patch without including changes made since the
3189 made by the current patch without including changes made since the
3199 qrefresh.
3190 qrefresh.
3200
3191
3201 Returns 0 on success.
3192 Returns 0 on success.
3202 """
3193 """
3203 ui.pager(b'qdiff')
3194 ui.pager(b'qdiff')
3204 repo.mq.diff(repo, pats, pycompat.byteskwargs(opts))
3195 repo.mq.diff(repo, pats, pycompat.byteskwargs(opts))
3205 return 0
3196 return 0
3206
3197
3207
3198
3208 @command(
3199 @command(
3209 b'qfold',
3200 b'qfold',
3210 [
3201 [
3211 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
3202 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
3212 (b'k', b'keep', None, _(b'keep folded patch files')),
3203 (b'k', b'keep', None, _(b'keep folded patch files')),
3213 ]
3204 ]
3214 + cmdutil.commitopts,
3205 + cmdutil.commitopts,
3215 _(b'hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'),
3206 _(b'hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'),
3216 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
3207 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
3217 )
3208 )
3218 def fold(ui, repo, *files, **opts):
3209 def fold(ui, repo, *files, **opts):
3219 """fold the named patches into the current patch
3210 """fold the named patches into the current patch
3220
3211
3221 Patches must not yet be applied. Each patch will be successively
3212 Patches must not yet be applied. Each patch will be successively
3222 applied to the current patch in the order given. If all the
3213 applied to the current patch in the order given. If all the
3223 patches apply successfully, the current patch will be refreshed
3214 patches apply successfully, the current patch will be refreshed
3224 with the new cumulative patch, and the folded patches will be
3215 with the new cumulative patch, and the folded patches will be
3225 deleted. With -k/--keep, the folded patch files will not be
3216 deleted. With -k/--keep, the folded patch files will not be
3226 removed afterwards.
3217 removed afterwards.
3227
3218
3228 The header for each folded patch will be concatenated with the
3219 The header for each folded patch will be concatenated with the
3229 current patch header, separated by a line of ``* * *``.
3220 current patch header, separated by a line of ``* * *``.
3230
3221
3231 Returns 0 on success."""
3222 Returns 0 on success."""
3232 opts = pycompat.byteskwargs(opts)
3223 opts = pycompat.byteskwargs(opts)
3233 q = repo.mq
3224 q = repo.mq
3234 if not files:
3225 if not files:
3235 raise error.Abort(_(b'qfold requires at least one patch name'))
3226 raise error.Abort(_(b'qfold requires at least one patch name'))
3236 if not q.checktoppatch(repo)[0]:
3227 if not q.checktoppatch(repo)[0]:
3237 raise error.Abort(_(b'no patches applied'))
3228 raise error.Abort(_(b'no patches applied'))
3238 q.checklocalchanges(repo)
3229 q.checklocalchanges(repo)
3239
3230
3240 message = cmdutil.logmessage(ui, opts)
3231 message = cmdutil.logmessage(ui, opts)
3241
3232
3242 parent = q.lookup(b'qtip')
3233 parent = q.lookup(b'qtip')
3243 patches = []
3234 patches = []
3244 messages = []
3235 messages = []
3245 for f in files:
3236 for f in files:
3246 p = q.lookup(f)
3237 p = q.lookup(f)
3247 if p in patches or p == parent:
3238 if p in patches or p == parent:
3248 ui.warn(_(b'skipping already folded patch %s\n') % p)
3239 ui.warn(_(b'skipping already folded patch %s\n') % p)
3249 if q.isapplied(p):
3240 if q.isapplied(p):
3250 raise error.Abort(
3241 raise error.Abort(
3251 _(b'qfold cannot fold already applied patch %s') % p
3242 _(b'qfold cannot fold already applied patch %s') % p
3252 )
3243 )
3253 patches.append(p)
3244 patches.append(p)
3254
3245
3255 for p in patches:
3246 for p in patches:
3256 if not message:
3247 if not message:
3257 ph = patchheader(q.join(p), q.plainmode)
3248 ph = patchheader(q.join(p), q.plainmode)
3258 if ph.message:
3249 if ph.message:
3259 messages.append(ph.message)
3250 messages.append(ph.message)
3260 pf = q.join(p)
3251 pf = q.join(p)
3261 (patchsuccess, files, fuzz) = q.patch(repo, pf)
3252 (patchsuccess, files, fuzz) = q.patch(repo, pf)
3262 if not patchsuccess:
3253 if not patchsuccess:
3263 raise error.Abort(_(b'error folding patch %s') % p)
3254 raise error.Abort(_(b'error folding patch %s') % p)
3264
3255
3265 if not message:
3256 if not message:
3266 ph = patchheader(q.join(parent), q.plainmode)
3257 ph = patchheader(q.join(parent), q.plainmode)
3267 message = ph.message
3258 message = ph.message
3268 for msg in messages:
3259 for msg in messages:
3269 if msg:
3260 if msg:
3270 if message:
3261 if message:
3271 message.append(b'* * *')
3262 message.append(b'* * *')
3272 message.extend(msg)
3263 message.extend(msg)
3273 message = b'\n'.join(message)
3264 message = b'\n'.join(message)
3274
3265
3275 diffopts = q.patchopts(q.diffopts(), *patches)
3266 diffopts = q.patchopts(q.diffopts(), *patches)
3276 with repo.wlock():
3267 with repo.wlock():
3277 q.refresh(
3268 q.refresh(
3278 repo,
3269 repo,
3279 msg=message,
3270 msg=message,
3280 git=diffopts.git,
3271 git=diffopts.git,
3281 edit=opts.get(b'edit'),
3272 edit=opts.get(b'edit'),
3282 editform=b'mq.qfold',
3273 editform=b'mq.qfold',
3283 )
3274 )
3284 q.delete(repo, patches, opts)
3275 q.delete(repo, patches, opts)
3285 q.savedirty()
3276 q.savedirty()
3286
3277
3287
3278
3288 @command(
3279 @command(
3289 b"qgoto",
3280 b"qgoto",
3290 [
3281 [
3291 (
3282 (
3292 b'',
3283 b'',
3293 b'keep-changes',
3284 b'keep-changes',
3294 None,
3285 None,
3295 _(b'tolerate non-conflicting local changes'),
3286 _(b'tolerate non-conflicting local changes'),
3296 ),
3287 ),
3297 (b'f', b'force', None, _(b'overwrite any local changes')),
3288 (b'f', b'force', None, _(b'overwrite any local changes')),
3298 (b'', b'no-backup', None, _(b'do not save backup copies of files')),
3289 (b'', b'no-backup', None, _(b'do not save backup copies of files')),
3299 ],
3290 ],
3300 _(b'hg qgoto [OPTION]... PATCH'),
3291 _(b'hg qgoto [OPTION]... PATCH'),
3301 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3292 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3302 )
3293 )
3303 def goto(ui, repo, patch, **opts):
3294 def goto(ui, repo, patch, **opts):
3304 """push or pop patches until named patch is at top of stack
3295 """push or pop patches until named patch is at top of stack
3305
3296
3306 Returns 0 on success."""
3297 Returns 0 on success."""
3307 opts = pycompat.byteskwargs(opts)
3298 opts = pycompat.byteskwargs(opts)
3308 opts = fixkeepchangesopts(ui, opts)
3299 opts = fixkeepchangesopts(ui, opts)
3309 q = repo.mq
3300 q = repo.mq
3310 patch = q.lookup(patch)
3301 patch = q.lookup(patch)
3311 nobackup = opts.get(b'no_backup')
3302 nobackup = opts.get(b'no_backup')
3312 keepchanges = opts.get(b'keep_changes')
3303 keepchanges = opts.get(b'keep_changes')
3313 if q.isapplied(patch):
3304 if q.isapplied(patch):
3314 ret = q.pop(
3305 ret = q.pop(
3315 repo,
3306 repo,
3316 patch,
3307 patch,
3317 force=opts.get(b'force'),
3308 force=opts.get(b'force'),
3318 nobackup=nobackup,
3309 nobackup=nobackup,
3319 keepchanges=keepchanges,
3310 keepchanges=keepchanges,
3320 )
3311 )
3321 else:
3312 else:
3322 ret = q.push(
3313 ret = q.push(
3323 repo,
3314 repo,
3324 patch,
3315 patch,
3325 force=opts.get(b'force'),
3316 force=opts.get(b'force'),
3326 nobackup=nobackup,
3317 nobackup=nobackup,
3327 keepchanges=keepchanges,
3318 keepchanges=keepchanges,
3328 )
3319 )
3329 q.savedirty()
3320 q.savedirty()
3330 return ret
3321 return ret
3331
3322
3332
3323
3333 @command(
3324 @command(
3334 b"qguard",
3325 b"qguard",
3335 [
3326 [
3336 (b'l', b'list', None, _(b'list all patches and guards')),
3327 (b'l', b'list', None, _(b'list all patches and guards')),
3337 (b'n', b'none', None, _(b'drop all guards')),
3328 (b'n', b'none', None, _(b'drop all guards')),
3338 ],
3329 ],
3339 _(b'hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'),
3330 _(b'hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'),
3340 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3331 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3341 )
3332 )
3342 def guard(ui, repo, *args, **opts):
3333 def guard(ui, repo, *args, **opts):
3343 """set or print guards for a patch
3334 """set or print guards for a patch
3344
3335
3345 Guards control whether a patch can be pushed. A patch with no
3336 Guards control whether a patch can be pushed. A patch with no
3346 guards is always pushed. A patch with a positive guard ("+foo") is
3337 guards is always pushed. A patch with a positive guard ("+foo") is
3347 pushed only if the :hg:`qselect` command has activated it. A patch with
3338 pushed only if the :hg:`qselect` command has activated it. A patch with
3348 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
3339 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
3349 has activated it.
3340 has activated it.
3350
3341
3351 With no arguments, print the currently active guards.
3342 With no arguments, print the currently active guards.
3352 With arguments, set guards for the named patch.
3343 With arguments, set guards for the named patch.
3353
3344
3354 .. note::
3345 .. note::
3355
3346
3356 Specifying negative guards now requires '--'.
3347 Specifying negative guards now requires '--'.
3357
3348
3358 To set guards on another patch::
3349 To set guards on another patch::
3359
3350
3360 hg qguard other.patch -- +2.6.17 -stable
3351 hg qguard other.patch -- +2.6.17 -stable
3361
3352
3362 Returns 0 on success.
3353 Returns 0 on success.
3363 """
3354 """
3364
3355
3365 def status(idx):
3356 def status(idx):
3366 guards = q.seriesguards[idx] or [b'unguarded']
3357 guards = q.seriesguards[idx] or [b'unguarded']
3367 if q.series[idx] in applied:
3358 if q.series[idx] in applied:
3368 state = b'applied'
3359 state = b'applied'
3369 elif q.pushable(idx)[0]:
3360 elif q.pushable(idx)[0]:
3370 state = b'unapplied'
3361 state = b'unapplied'
3371 else:
3362 else:
3372 state = b'guarded'
3363 state = b'guarded'
3373 label = b'qguard.patch qguard.%s qseries.%s' % (state, state)
3364 label = b'qguard.patch qguard.%s qseries.%s' % (state, state)
3374 ui.write(b'%s: ' % ui.label(q.series[idx], label))
3365 ui.write(b'%s: ' % ui.label(q.series[idx], label))
3375
3366
3376 for i, guard in enumerate(guards):
3367 for i, guard in enumerate(guards):
3377 if guard.startswith(b'+'):
3368 if guard.startswith(b'+'):
3378 ui.write(guard, label=b'qguard.positive')
3369 ui.write(guard, label=b'qguard.positive')
3379 elif guard.startswith(b'-'):
3370 elif guard.startswith(b'-'):
3380 ui.write(guard, label=b'qguard.negative')
3371 ui.write(guard, label=b'qguard.negative')
3381 else:
3372 else:
3382 ui.write(guard, label=b'qguard.unguarded')
3373 ui.write(guard, label=b'qguard.unguarded')
3383 if i != len(guards) - 1:
3374 if i != len(guards) - 1:
3384 ui.write(b' ')
3375 ui.write(b' ')
3385 ui.write(b'\n')
3376 ui.write(b'\n')
3386
3377
3387 q = repo.mq
3378 q = repo.mq
3388 applied = {p.name for p in q.applied}
3379 applied = {p.name for p in q.applied}
3389 patch = None
3380 patch = None
3390 args = list(args)
3381 args = list(args)
3391 if opts.get('list'):
3382 if opts.get('list'):
3392 if args or opts.get('none'):
3383 if args or opts.get('none'):
3393 raise error.Abort(
3384 raise error.Abort(
3394 _(b'cannot mix -l/--list with options or arguments')
3385 _(b'cannot mix -l/--list with options or arguments')
3395 )
3386 )
3396 for i in pycompat.xrange(len(q.series)):
3387 for i in pycompat.xrange(len(q.series)):
3397 status(i)
3388 status(i)
3398 return
3389 return
3399 if not args or args[0][0:1] in b'-+':
3390 if not args or args[0][0:1] in b'-+':
3400 if not q.applied:
3391 if not q.applied:
3401 raise error.Abort(_(b'no patches applied'))
3392 raise error.Abort(_(b'no patches applied'))
3402 patch = q.applied[-1].name
3393 patch = q.applied[-1].name
3403 if patch is None and args[0][0:1] not in b'-+':
3394 if patch is None and args[0][0:1] not in b'-+':
3404 patch = args.pop(0)
3395 patch = args.pop(0)
3405 if patch is None:
3396 if patch is None:
3406 raise error.Abort(_(b'no patch to work with'))
3397 raise error.Abort(_(b'no patch to work with'))
3407 if args or opts.get('none'):
3398 if args or opts.get('none'):
3408 idx = q.findseries(patch)
3399 idx = q.findseries(patch)
3409 if idx is None:
3400 if idx is None:
3410 raise error.Abort(_(b'no patch named %s') % patch)
3401 raise error.Abort(_(b'no patch named %s') % patch)
3411 q.setguards(idx, args)
3402 q.setguards(idx, args)
3412 q.savedirty()
3403 q.savedirty()
3413 else:
3404 else:
3414 status(q.series.index(q.lookup(patch)))
3405 status(q.series.index(q.lookup(patch)))
3415
3406
3416
3407
3417 @command(
3408 @command(
3418 b"qheader",
3409 b"qheader",
3419 [],
3410 [],
3420 _(b'hg qheader [PATCH]'),
3411 _(b'hg qheader [PATCH]'),
3421 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3412 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3422 )
3413 )
3423 def header(ui, repo, patch=None):
3414 def header(ui, repo, patch=None):
3424 """print the header of the topmost or specified patch
3415 """print the header of the topmost or specified patch
3425
3416
3426 Returns 0 on success."""
3417 Returns 0 on success."""
3427 q = repo.mq
3418 q = repo.mq
3428
3419
3429 if patch:
3420 if patch:
3430 patch = q.lookup(patch)
3421 patch = q.lookup(patch)
3431 else:
3422 else:
3432 if not q.applied:
3423 if not q.applied:
3433 ui.write(_(b'no patches applied\n'))
3424 ui.write(_(b'no patches applied\n'))
3434 return 1
3425 return 1
3435 patch = q.lookup(b'qtip')
3426 patch = q.lookup(b'qtip')
3436 ph = patchheader(q.join(patch), q.plainmode)
3427 ph = patchheader(q.join(patch), q.plainmode)
3437
3428
3438 ui.write(b'\n'.join(ph.message) + b'\n')
3429 ui.write(b'\n'.join(ph.message) + b'\n')
3439
3430
3440
3431
3441 def lastsavename(path):
3432 def lastsavename(path):
3442 (directory, base) = os.path.split(path)
3433 (directory, base) = os.path.split(path)
3443 names = os.listdir(directory)
3434 names = os.listdir(directory)
3444 namere = re.compile(b"%s.([0-9]+)" % base)
3435 namere = re.compile(b"%s.([0-9]+)" % base)
3445 maxindex = None
3436 maxindex = None
3446 maxname = None
3437 maxname = None
3447 for f in names:
3438 for f in names:
3448 m = namere.match(f)
3439 m = namere.match(f)
3449 if m:
3440 if m:
3450 index = int(m.group(1))
3441 index = int(m.group(1))
3451 if maxindex is None or index > maxindex:
3442 if maxindex is None or index > maxindex:
3452 maxindex = index
3443 maxindex = index
3453 maxname = f
3444 maxname = f
3454 if maxname:
3445 if maxname:
3455 return (os.path.join(directory, maxname), maxindex)
3446 return (os.path.join(directory, maxname), maxindex)
3456 return (None, None)
3447 return (None, None)
3457
3448
3458
3449
3459 def savename(path):
3450 def savename(path):
3460 (last, index) = lastsavename(path)
3451 (last, index) = lastsavename(path)
3461 if last is None:
3452 if last is None:
3462 index = 0
3453 index = 0
3463 newpath = path + b".%d" % (index + 1)
3454 newpath = path + b".%d" % (index + 1)
3464 return newpath
3455 return newpath
3465
3456
3466
3457
3467 @command(
3458 @command(
3468 b"qpush",
3459 b"qpush",
3469 [
3460 [
3470 (
3461 (
3471 b'',
3462 b'',
3472 b'keep-changes',
3463 b'keep-changes',
3473 None,
3464 None,
3474 _(b'tolerate non-conflicting local changes'),
3465 _(b'tolerate non-conflicting local changes'),
3475 ),
3466 ),
3476 (b'f', b'force', None, _(b'apply on top of local changes')),
3467 (b'f', b'force', None, _(b'apply on top of local changes')),
3477 (
3468 (
3478 b'e',
3469 b'e',
3479 b'exact',
3470 b'exact',
3480 None,
3471 None,
3481 _(b'apply the target patch to its recorded parent'),
3472 _(b'apply the target patch to its recorded parent'),
3482 ),
3473 ),
3483 (b'l', b'list', None, _(b'list patch name in commit text')),
3474 (b'l', b'list', None, _(b'list patch name in commit text')),
3484 (b'a', b'all', None, _(b'apply all patches')),
3475 (b'a', b'all', None, _(b'apply all patches')),
3485 (b'm', b'merge', None, _(b'merge from another queue (DEPRECATED)')),
3476 (b'm', b'merge', None, _(b'merge from another queue (DEPRECATED)')),
3486 (b'n', b'name', b'', _(b'merge queue name (DEPRECATED)'), _(b'NAME')),
3477 (b'n', b'name', b'', _(b'merge queue name (DEPRECATED)'), _(b'NAME')),
3487 (
3478 (
3488 b'',
3479 b'',
3489 b'move',
3480 b'move',
3490 None,
3481 None,
3491 _(b'reorder patch series and apply only the patch'),
3482 _(b'reorder patch series and apply only the patch'),
3492 ),
3483 ),
3493 (b'', b'no-backup', None, _(b'do not save backup copies of files')),
3484 (b'', b'no-backup', None, _(b'do not save backup copies of files')),
3494 ],
3485 ],
3495 _(b'hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'),
3486 _(b'hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'),
3496 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3487 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3497 helpbasic=True,
3488 helpbasic=True,
3498 )
3489 )
3499 def push(ui, repo, patch=None, **opts):
3490 def push(ui, repo, patch=None, **opts):
3500 """push the next patch onto the stack
3491 """push the next patch onto the stack
3501
3492
3502 By default, abort if the working directory contains uncommitted
3493 By default, abort if the working directory contains uncommitted
3503 changes. With --keep-changes, abort only if the uncommitted files
3494 changes. With --keep-changes, abort only if the uncommitted files
3504 overlap with patched files. With -f/--force, backup and patch over
3495 overlap with patched files. With -f/--force, backup and patch over
3505 uncommitted changes.
3496 uncommitted changes.
3506
3497
3507 Return 0 on success.
3498 Return 0 on success.
3508 """
3499 """
3509 q = repo.mq
3500 q = repo.mq
3510 mergeq = None
3501 mergeq = None
3511
3502
3512 opts = pycompat.byteskwargs(opts)
3503 opts = pycompat.byteskwargs(opts)
3513 opts = fixkeepchangesopts(ui, opts)
3504 opts = fixkeepchangesopts(ui, opts)
3514 if opts.get(b'merge'):
3505 if opts.get(b'merge'):
3515 if opts.get(b'name'):
3506 if opts.get(b'name'):
3516 newpath = repo.vfs.join(opts.get(b'name'))
3507 newpath = repo.vfs.join(opts.get(b'name'))
3517 else:
3508 else:
3518 newpath, i = lastsavename(q.path)
3509 newpath, i = lastsavename(q.path)
3519 if not newpath:
3510 if not newpath:
3520 ui.warn(_(b"no saved queues found, please use -n\n"))
3511 ui.warn(_(b"no saved queues found, please use -n\n"))
3521 return 1
3512 return 1
3522 mergeq = queue(ui, repo.baseui, repo.path, newpath)
3513 mergeq = queue(ui, repo.baseui, repo.path, newpath)
3523 ui.warn(_(b"merging with queue at: %s\n") % mergeq.path)
3514 ui.warn(_(b"merging with queue at: %s\n") % mergeq.path)
3524 ret = q.push(
3515 ret = q.push(
3525 repo,
3516 repo,
3526 patch,
3517 patch,
3527 force=opts.get(b'force'),
3518 force=opts.get(b'force'),
3528 list=opts.get(b'list'),
3519 list=opts.get(b'list'),
3529 mergeq=mergeq,
3520 mergeq=mergeq,
3530 all=opts.get(b'all'),
3521 all=opts.get(b'all'),
3531 move=opts.get(b'move'),
3522 move=opts.get(b'move'),
3532 exact=opts.get(b'exact'),
3523 exact=opts.get(b'exact'),
3533 nobackup=opts.get(b'no_backup'),
3524 nobackup=opts.get(b'no_backup'),
3534 keepchanges=opts.get(b'keep_changes'),
3525 keepchanges=opts.get(b'keep_changes'),
3535 )
3526 )
3536 return ret
3527 return ret
3537
3528
3538
3529
3539 @command(
3530 @command(
3540 b"qpop",
3531 b"qpop",
3541 [
3532 [
3542 (b'a', b'all', None, _(b'pop all patches')),
3533 (b'a', b'all', None, _(b'pop all patches')),
3543 (b'n', b'name', b'', _(b'queue name to pop (DEPRECATED)'), _(b'NAME')),
3534 (b'n', b'name', b'', _(b'queue name to pop (DEPRECATED)'), _(b'NAME')),
3544 (
3535 (
3545 b'',
3536 b'',
3546 b'keep-changes',
3537 b'keep-changes',
3547 None,
3538 None,
3548 _(b'tolerate non-conflicting local changes'),
3539 _(b'tolerate non-conflicting local changes'),
3549 ),
3540 ),
3550 (b'f', b'force', None, _(b'forget any local changes to patched files')),
3541 (b'f', b'force', None, _(b'forget any local changes to patched files')),
3551 (b'', b'no-backup', None, _(b'do not save backup copies of files')),
3542 (b'', b'no-backup', None, _(b'do not save backup copies of files')),
3552 ],
3543 ],
3553 _(b'hg qpop [-a] [-f] [PATCH | INDEX]'),
3544 _(b'hg qpop [-a] [-f] [PATCH | INDEX]'),
3554 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3545 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3555 helpbasic=True,
3546 helpbasic=True,
3556 )
3547 )
3557 def pop(ui, repo, patch=None, **opts):
3548 def pop(ui, repo, patch=None, **opts):
3558 """pop the current patch off the stack
3549 """pop the current patch off the stack
3559
3550
3560 Without argument, pops off the top of the patch stack. If given a
3551 Without argument, pops off the top of the patch stack. If given a
3561 patch name, keeps popping off patches until the named patch is at
3552 patch name, keeps popping off patches until the named patch is at
3562 the top of the stack.
3553 the top of the stack.
3563
3554
3564 By default, abort if the working directory contains uncommitted
3555 By default, abort if the working directory contains uncommitted
3565 changes. With --keep-changes, abort only if the uncommitted files
3556 changes. With --keep-changes, abort only if the uncommitted files
3566 overlap with patched files. With -f/--force, backup and discard
3557 overlap with patched files. With -f/--force, backup and discard
3567 changes made to such files.
3558 changes made to such files.
3568
3559
3569 Return 0 on success.
3560 Return 0 on success.
3570 """
3561 """
3571 opts = pycompat.byteskwargs(opts)
3562 opts = pycompat.byteskwargs(opts)
3572 opts = fixkeepchangesopts(ui, opts)
3563 opts = fixkeepchangesopts(ui, opts)
3573 localupdate = True
3564 localupdate = True
3574 if opts.get(b'name'):
3565 if opts.get(b'name'):
3575 q = queue(ui, repo.baseui, repo.path, repo.vfs.join(opts.get(b'name')))
3566 q = queue(ui, repo.baseui, repo.path, repo.vfs.join(opts.get(b'name')))
3576 ui.warn(_(b'using patch queue: %s\n') % q.path)
3567 ui.warn(_(b'using patch queue: %s\n') % q.path)
3577 localupdate = False
3568 localupdate = False
3578 else:
3569 else:
3579 q = repo.mq
3570 q = repo.mq
3580 ret = q.pop(
3571 ret = q.pop(
3581 repo,
3572 repo,
3582 patch,
3573 patch,
3583 force=opts.get(b'force'),
3574 force=opts.get(b'force'),
3584 update=localupdate,
3575 update=localupdate,
3585 all=opts.get(b'all'),
3576 all=opts.get(b'all'),
3586 nobackup=opts.get(b'no_backup'),
3577 nobackup=opts.get(b'no_backup'),
3587 keepchanges=opts.get(b'keep_changes'),
3578 keepchanges=opts.get(b'keep_changes'),
3588 )
3579 )
3589 q.savedirty()
3580 q.savedirty()
3590 return ret
3581 return ret
3591
3582
3592
3583
3593 @command(
3584 @command(
3594 b"qrename|qmv",
3585 b"qrename|qmv",
3595 [],
3586 [],
3596 _(b'hg qrename PATCH1 [PATCH2]'),
3587 _(b'hg qrename PATCH1 [PATCH2]'),
3597 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3588 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3598 )
3589 )
3599 def rename(ui, repo, patch, name=None, **opts):
3590 def rename(ui, repo, patch, name=None, **opts):
3600 """rename a patch
3591 """rename a patch
3601
3592
3602 With one argument, renames the current patch to PATCH1.
3593 With one argument, renames the current patch to PATCH1.
3603 With two arguments, renames PATCH1 to PATCH2.
3594 With two arguments, renames PATCH1 to PATCH2.
3604
3595
3605 Returns 0 on success."""
3596 Returns 0 on success."""
3606 q = repo.mq
3597 q = repo.mq
3607 if not name:
3598 if not name:
3608 name = patch
3599 name = patch
3609 patch = None
3600 patch = None
3610
3601
3611 if patch:
3602 if patch:
3612 patch = q.lookup(patch)
3603 patch = q.lookup(patch)
3613 else:
3604 else:
3614 if not q.applied:
3605 if not q.applied:
3615 ui.write(_(b'no patches applied\n'))
3606 ui.write(_(b'no patches applied\n'))
3616 return
3607 return
3617 patch = q.lookup(b'qtip')
3608 patch = q.lookup(b'qtip')
3618 absdest = q.join(name)
3609 absdest = q.join(name)
3619 if os.path.isdir(absdest):
3610 if os.path.isdir(absdest):
3620 name = normname(os.path.join(name, os.path.basename(patch)))
3611 name = normname(os.path.join(name, os.path.basename(patch)))
3621 absdest = q.join(name)
3612 absdest = q.join(name)
3622 q.checkpatchname(name)
3613 q.checkpatchname(name)
3623
3614
3624 ui.note(_(b'renaming %s to %s\n') % (patch, name))
3615 ui.note(_(b'renaming %s to %s\n') % (patch, name))
3625 i = q.findseries(patch)
3616 i = q.findseries(patch)
3626 guards = q.guard_re.findall(q.fullseries[i])
3617 guards = q.guard_re.findall(q.fullseries[i])
3627 q.fullseries[i] = name + b''.join([b' #' + g for g in guards])
3618 q.fullseries[i] = name + b''.join([b' #' + g for g in guards])
3628 q.parseseries()
3619 q.parseseries()
3629 q.seriesdirty = True
3620 q.seriesdirty = True
3630
3621
3631 info = q.isapplied(patch)
3622 info = q.isapplied(patch)
3632 if info:
3623 if info:
3633 q.applied[info[0]] = statusentry(info[1], name)
3624 q.applied[info[0]] = statusentry(info[1], name)
3634 q.applieddirty = True
3625 q.applieddirty = True
3635
3626
3636 destdir = os.path.dirname(absdest)
3627 destdir = os.path.dirname(absdest)
3637 if not os.path.isdir(destdir):
3628 if not os.path.isdir(destdir):
3638 os.makedirs(destdir)
3629 os.makedirs(destdir)
3639 util.rename(q.join(patch), absdest)
3630 util.rename(q.join(patch), absdest)
3640 r = q.qrepo()
3631 r = q.qrepo()
3641 if r and patch in r.dirstate:
3632 if r and patch in r.dirstate:
3642 wctx = r[None]
3633 wctx = r[None]
3643 with r.wlock():
3634 with r.wlock():
3644 if r.dirstate[patch] == b'a':
3635 if r.dirstate[patch] == b'a':
3645 r.dirstate.set_untracked(patch)
3636 r.dirstate.set_untracked(patch)
3646 r.dirstate.set_tracked(name)
3637 r.dirstate.set_tracked(name)
3647 else:
3638 else:
3648 wctx.copy(patch, name)
3639 wctx.copy(patch, name)
3649 wctx.forget([patch])
3640 wctx.forget([patch])
3650
3641
3651 q.savedirty()
3642 q.savedirty()
3652
3643
3653
3644
3654 @command(
3645 @command(
3655 b"qrestore",
3646 b"qrestore",
3656 [
3647 [
3657 (b'd', b'delete', None, _(b'delete save entry')),
3648 (b'd', b'delete', None, _(b'delete save entry')),
3658 (b'u', b'update', None, _(b'update queue working directory')),
3649 (b'u', b'update', None, _(b'update queue working directory')),
3659 ],
3650 ],
3660 _(b'hg qrestore [-d] [-u] REV'),
3651 _(b'hg qrestore [-d] [-u] REV'),
3661 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3652 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3662 )
3653 )
3663 def restore(ui, repo, rev, **opts):
3654 def restore(ui, repo, rev, **opts):
3664 """restore the queue state saved by a revision (DEPRECATED)
3655 """restore the queue state saved by a revision (DEPRECATED)
3665
3656
3666 This command is deprecated, use :hg:`rebase` instead."""
3657 This command is deprecated, use :hg:`rebase` instead."""
3667 rev = repo.lookup(rev)
3658 rev = repo.lookup(rev)
3668 q = repo.mq
3659 q = repo.mq
3669 q.restore(repo, rev, delete=opts.get('delete'), qupdate=opts.get('update'))
3660 q.restore(repo, rev, delete=opts.get('delete'), qupdate=opts.get('update'))
3670 q.savedirty()
3661 q.savedirty()
3671 return 0
3662 return 0
3672
3663
3673
3664
3674 @command(
3665 @command(
3675 b"qsave",
3666 b"qsave",
3676 [
3667 [
3677 (b'c', b'copy', None, _(b'copy patch directory')),
3668 (b'c', b'copy', None, _(b'copy patch directory')),
3678 (b'n', b'name', b'', _(b'copy directory name'), _(b'NAME')),
3669 (b'n', b'name', b'', _(b'copy directory name'), _(b'NAME')),
3679 (b'e', b'empty', None, _(b'clear queue status file')),
3670 (b'e', b'empty', None, _(b'clear queue status file')),
3680 (b'f', b'force', None, _(b'force copy')),
3671 (b'f', b'force', None, _(b'force copy')),
3681 ]
3672 ]
3682 + cmdutil.commitopts,
3673 + cmdutil.commitopts,
3683 _(b'hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'),
3674 _(b'hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'),
3684 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3675 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3685 )
3676 )
3686 def save(ui, repo, **opts):
3677 def save(ui, repo, **opts):
3687 """save current queue state (DEPRECATED)
3678 """save current queue state (DEPRECATED)
3688
3679
3689 This command is deprecated, use :hg:`rebase` instead."""
3680 This command is deprecated, use :hg:`rebase` instead."""
3690 q = repo.mq
3681 q = repo.mq
3691 opts = pycompat.byteskwargs(opts)
3682 opts = pycompat.byteskwargs(opts)
3692 message = cmdutil.logmessage(ui, opts)
3683 message = cmdutil.logmessage(ui, opts)
3693 ret = q.save(repo, msg=message)
3684 ret = q.save(repo, msg=message)
3694 if ret:
3685 if ret:
3695 return ret
3686 return ret
3696 q.savedirty() # save to .hg/patches before copying
3687 q.savedirty() # save to .hg/patches before copying
3697 if opts.get(b'copy'):
3688 if opts.get(b'copy'):
3698 path = q.path
3689 path = q.path
3699 if opts.get(b'name'):
3690 if opts.get(b'name'):
3700 newpath = os.path.join(q.basepath, opts.get(b'name'))
3691 newpath = os.path.join(q.basepath, opts.get(b'name'))
3701 if os.path.exists(newpath):
3692 if os.path.exists(newpath):
3702 if not os.path.isdir(newpath):
3693 if not os.path.isdir(newpath):
3703 raise error.Abort(
3694 raise error.Abort(
3704 _(b'destination %s exists and is not a directory')
3695 _(b'destination %s exists and is not a directory')
3705 % newpath
3696 % newpath
3706 )
3697 )
3707 if not opts.get(b'force'):
3698 if not opts.get(b'force'):
3708 raise error.Abort(
3699 raise error.Abort(
3709 _(b'destination %s exists, use -f to force') % newpath
3700 _(b'destination %s exists, use -f to force') % newpath
3710 )
3701 )
3711 else:
3702 else:
3712 newpath = savename(path)
3703 newpath = savename(path)
3713 ui.warn(_(b"copy %s to %s\n") % (path, newpath))
3704 ui.warn(_(b"copy %s to %s\n") % (path, newpath))
3714 util.copyfiles(path, newpath)
3705 util.copyfiles(path, newpath)
3715 if opts.get(b'empty'):
3706 if opts.get(b'empty'):
3716 del q.applied[:]
3707 del q.applied[:]
3717 q.applieddirty = True
3708 q.applieddirty = True
3718 q.savedirty()
3709 q.savedirty()
3719 return 0
3710 return 0
3720
3711
3721
3712
3722 @command(
3713 @command(
3723 b"qselect",
3714 b"qselect",
3724 [
3715 [
3725 (b'n', b'none', None, _(b'disable all guards')),
3716 (b'n', b'none', None, _(b'disable all guards')),
3726 (b's', b'series', None, _(b'list all guards in series file')),
3717 (b's', b'series', None, _(b'list all guards in series file')),
3727 (b'', b'pop', None, _(b'pop to before first guarded applied patch')),
3718 (b'', b'pop', None, _(b'pop to before first guarded applied patch')),
3728 (b'', b'reapply', None, _(b'pop, then reapply patches')),
3719 (b'', b'reapply', None, _(b'pop, then reapply patches')),
3729 ],
3720 ],
3730 _(b'hg qselect [OPTION]... [GUARD]...'),
3721 _(b'hg qselect [OPTION]... [GUARD]...'),
3731 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3722 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3732 )
3723 )
3733 def select(ui, repo, *args, **opts):
3724 def select(ui, repo, *args, **opts):
3734 """set or print guarded patches to push
3725 """set or print guarded patches to push
3735
3726
3736 Use the :hg:`qguard` command to set or print guards on patch, then use
3727 Use the :hg:`qguard` command to set or print guards on patch, then use
3737 qselect to tell mq which guards to use. A patch will be pushed if
3728 qselect to tell mq which guards to use. A patch will be pushed if
3738 it has no guards or any positive guards match the currently
3729 it has no guards or any positive guards match the currently
3739 selected guard, but will not be pushed if any negative guards
3730 selected guard, but will not be pushed if any negative guards
3740 match the current guard. For example::
3731 match the current guard. For example::
3741
3732
3742 qguard foo.patch -- -stable (negative guard)
3733 qguard foo.patch -- -stable (negative guard)
3743 qguard bar.patch +stable (positive guard)
3734 qguard bar.patch +stable (positive guard)
3744 qselect stable
3735 qselect stable
3745
3736
3746 This activates the "stable" guard. mq will skip foo.patch (because
3737 This activates the "stable" guard. mq will skip foo.patch (because
3747 it has a negative match) but push bar.patch (because it has a
3738 it has a negative match) but push bar.patch (because it has a
3748 positive match).
3739 positive match).
3749
3740
3750 With no arguments, prints the currently active guards.
3741 With no arguments, prints the currently active guards.
3751 With one argument, sets the active guard.
3742 With one argument, sets the active guard.
3752
3743
3753 Use -n/--none to deactivate guards (no other arguments needed).
3744 Use -n/--none to deactivate guards (no other arguments needed).
3754 When no guards are active, patches with positive guards are
3745 When no guards are active, patches with positive guards are
3755 skipped and patches with negative guards are pushed.
3746 skipped and patches with negative guards are pushed.
3756
3747
3757 qselect can change the guards on applied patches. It does not pop
3748 qselect can change the guards on applied patches. It does not pop
3758 guarded patches by default. Use --pop to pop back to the last
3749 guarded patches by default. Use --pop to pop back to the last
3759 applied patch that is not guarded. Use --reapply (which implies
3750 applied patch that is not guarded. Use --reapply (which implies
3760 --pop) to push back to the current patch afterwards, but skip
3751 --pop) to push back to the current patch afterwards, but skip
3761 guarded patches.
3752 guarded patches.
3762
3753
3763 Use -s/--series to print a list of all guards in the series file
3754 Use -s/--series to print a list of all guards in the series file
3764 (no other arguments needed). Use -v for more information.
3755 (no other arguments needed). Use -v for more information.
3765
3756
3766 Returns 0 on success."""
3757 Returns 0 on success."""
3767
3758
3768 q = repo.mq
3759 q = repo.mq
3769 opts = pycompat.byteskwargs(opts)
3760 opts = pycompat.byteskwargs(opts)
3770 guards = q.active()
3761 guards = q.active()
3771 pushable = lambda i: q.pushable(q.applied[i].name)[0]
3762 pushable = lambda i: q.pushable(q.applied[i].name)[0]
3772 if args or opts.get(b'none'):
3763 if args or opts.get(b'none'):
3773 old_unapplied = q.unapplied(repo)
3764 old_unapplied = q.unapplied(repo)
3774 old_guarded = [
3765 old_guarded = [
3775 i for i in pycompat.xrange(len(q.applied)) if not pushable(i)
3766 i for i in pycompat.xrange(len(q.applied)) if not pushable(i)
3776 ]
3767 ]
3777 q.setactive(args)
3768 q.setactive(args)
3778 q.savedirty()
3769 q.savedirty()
3779 if not args:
3770 if not args:
3780 ui.status(_(b'guards deactivated\n'))
3771 ui.status(_(b'guards deactivated\n'))
3781 if not opts.get(b'pop') and not opts.get(b'reapply'):
3772 if not opts.get(b'pop') and not opts.get(b'reapply'):
3782 unapplied = q.unapplied(repo)
3773 unapplied = q.unapplied(repo)
3783 guarded = [
3774 guarded = [
3784 i for i in pycompat.xrange(len(q.applied)) if not pushable(i)
3775 i for i in pycompat.xrange(len(q.applied)) if not pushable(i)
3785 ]
3776 ]
3786 if len(unapplied) != len(old_unapplied):
3777 if len(unapplied) != len(old_unapplied):
3787 ui.status(
3778 ui.status(
3788 _(
3779 _(
3789 b'number of unguarded, unapplied patches has '
3780 b'number of unguarded, unapplied patches has '
3790 b'changed from %d to %d\n'
3781 b'changed from %d to %d\n'
3791 )
3782 )
3792 % (len(old_unapplied), len(unapplied))
3783 % (len(old_unapplied), len(unapplied))
3793 )
3784 )
3794 if len(guarded) != len(old_guarded):
3785 if len(guarded) != len(old_guarded):
3795 ui.status(
3786 ui.status(
3796 _(
3787 _(
3797 b'number of guarded, applied patches has changed '
3788 b'number of guarded, applied patches has changed '
3798 b'from %d to %d\n'
3789 b'from %d to %d\n'
3799 )
3790 )
3800 % (len(old_guarded), len(guarded))
3791 % (len(old_guarded), len(guarded))
3801 )
3792 )
3802 elif opts.get(b'series'):
3793 elif opts.get(b'series'):
3803 guards = {}
3794 guards = {}
3804 noguards = 0
3795 noguards = 0
3805 for gs in q.seriesguards:
3796 for gs in q.seriesguards:
3806 if not gs:
3797 if not gs:
3807 noguards += 1
3798 noguards += 1
3808 for g in gs:
3799 for g in gs:
3809 guards.setdefault(g, 0)
3800 guards.setdefault(g, 0)
3810 guards[g] += 1
3801 guards[g] += 1
3811 if ui.verbose:
3802 if ui.verbose:
3812 guards[b'NONE'] = noguards
3803 guards[b'NONE'] = noguards
3813 guards = list(guards.items())
3804 guards = list(guards.items())
3814 guards.sort(key=lambda x: x[0][1:])
3805 guards.sort(key=lambda x: x[0][1:])
3815 if guards:
3806 if guards:
3816 ui.note(_(b'guards in series file:\n'))
3807 ui.note(_(b'guards in series file:\n'))
3817 for guard, count in guards:
3808 for guard, count in guards:
3818 ui.note(b'%2d ' % count)
3809 ui.note(b'%2d ' % count)
3819 ui.write(guard, b'\n')
3810 ui.write(guard, b'\n')
3820 else:
3811 else:
3821 ui.note(_(b'no guards in series file\n'))
3812 ui.note(_(b'no guards in series file\n'))
3822 else:
3813 else:
3823 if guards:
3814 if guards:
3824 ui.note(_(b'active guards:\n'))
3815 ui.note(_(b'active guards:\n'))
3825 for g in guards:
3816 for g in guards:
3826 ui.write(g, b'\n')
3817 ui.write(g, b'\n')
3827 else:
3818 else:
3828 ui.write(_(b'no active guards\n'))
3819 ui.write(_(b'no active guards\n'))
3829 reapply = opts.get(b'reapply') and q.applied and q.applied[-1].name
3820 reapply = opts.get(b'reapply') and q.applied and q.applied[-1].name
3830 popped = False
3821 popped = False
3831 if opts.get(b'pop') or opts.get(b'reapply'):
3822 if opts.get(b'pop') or opts.get(b'reapply'):
3832 for i in pycompat.xrange(len(q.applied)):
3823 for i in pycompat.xrange(len(q.applied)):
3833 if not pushable(i):
3824 if not pushable(i):
3834 ui.status(_(b'popping guarded patches\n'))
3825 ui.status(_(b'popping guarded patches\n'))
3835 popped = True
3826 popped = True
3836 if i == 0:
3827 if i == 0:
3837 q.pop(repo, all=True)
3828 q.pop(repo, all=True)
3838 else:
3829 else:
3839 q.pop(repo, q.applied[i - 1].name)
3830 q.pop(repo, q.applied[i - 1].name)
3840 break
3831 break
3841 if popped:
3832 if popped:
3842 try:
3833 try:
3843 if reapply:
3834 if reapply:
3844 ui.status(_(b'reapplying unguarded patches\n'))
3835 ui.status(_(b'reapplying unguarded patches\n'))
3845 q.push(repo, reapply)
3836 q.push(repo, reapply)
3846 finally:
3837 finally:
3847 q.savedirty()
3838 q.savedirty()
3848
3839
3849
3840
3850 @command(
3841 @command(
3851 b"qfinish",
3842 b"qfinish",
3852 [(b'a', b'applied', None, _(b'finish all applied changesets'))],
3843 [(b'a', b'applied', None, _(b'finish all applied changesets'))],
3853 _(b'hg qfinish [-a] [REV]...'),
3844 _(b'hg qfinish [-a] [REV]...'),
3854 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3845 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3855 )
3846 )
3856 def finish(ui, repo, *revrange, **opts):
3847 def finish(ui, repo, *revrange, **opts):
3857 """move applied patches into repository history
3848 """move applied patches into repository history
3858
3849
3859 Finishes the specified revisions (corresponding to applied
3850 Finishes the specified revisions (corresponding to applied
3860 patches) by moving them out of mq control into regular repository
3851 patches) by moving them out of mq control into regular repository
3861 history.
3852 history.
3862
3853
3863 Accepts a revision range or the -a/--applied option. If --applied
3854 Accepts a revision range or the -a/--applied option. If --applied
3864 is specified, all applied mq revisions are removed from mq
3855 is specified, all applied mq revisions are removed from mq
3865 control. Otherwise, the given revisions must be at the base of the
3856 control. Otherwise, the given revisions must be at the base of the
3866 stack of applied patches.
3857 stack of applied patches.
3867
3858
3868 This can be especially useful if your changes have been applied to
3859 This can be especially useful if your changes have been applied to
3869 an upstream repository, or if you are about to push your changes
3860 an upstream repository, or if you are about to push your changes
3870 to upstream.
3861 to upstream.
3871
3862
3872 Returns 0 on success.
3863 Returns 0 on success.
3873 """
3864 """
3874 if not opts.get('applied') and not revrange:
3865 if not opts.get('applied') and not revrange:
3875 raise error.Abort(_(b'no revisions specified'))
3866 raise error.Abort(_(b'no revisions specified'))
3876 elif opts.get('applied'):
3867 elif opts.get('applied'):
3877 revrange = (b'qbase::qtip',) + revrange
3868 revrange = (b'qbase::qtip',) + revrange
3878
3869
3879 q = repo.mq
3870 q = repo.mq
3880 if not q.applied:
3871 if not q.applied:
3881 ui.status(_(b'no patches applied\n'))
3872 ui.status(_(b'no patches applied\n'))
3882 return 0
3873 return 0
3883
3874
3884 revs = scmutil.revrange(repo, revrange)
3875 revs = scmutil.revrange(repo, revrange)
3885 if repo[b'.'].rev() in revs and repo[None].files():
3876 if repo[b'.'].rev() in revs and repo[None].files():
3886 ui.warn(_(b'warning: uncommitted changes in the working directory\n'))
3877 ui.warn(_(b'warning: uncommitted changes in the working directory\n'))
3887 # queue.finish may changes phases but leave the responsibility to lock the
3878 # queue.finish may changes phases but leave the responsibility to lock the
3888 # repo to the caller to avoid deadlock with wlock. This command code is
3879 # repo to the caller to avoid deadlock with wlock. This command code is
3889 # responsibility for this locking.
3880 # responsibility for this locking.
3890 with repo.lock():
3881 with repo.lock():
3891 q.finish(repo, revs)
3882 q.finish(repo, revs)
3892 q.savedirty()
3883 q.savedirty()
3893 return 0
3884 return 0
3894
3885
3895
3886
3896 @command(
3887 @command(
3897 b"qqueue",
3888 b"qqueue",
3898 [
3889 [
3899 (b'l', b'list', False, _(b'list all available queues')),
3890 (b'l', b'list', False, _(b'list all available queues')),
3900 (b'', b'active', False, _(b'print name of active queue')),
3891 (b'', b'active', False, _(b'print name of active queue')),
3901 (b'c', b'create', False, _(b'create new queue')),
3892 (b'c', b'create', False, _(b'create new queue')),
3902 (b'', b'rename', False, _(b'rename active queue')),
3893 (b'', b'rename', False, _(b'rename active queue')),
3903 (b'', b'delete', False, _(b'delete reference to queue')),
3894 (b'', b'delete', False, _(b'delete reference to queue')),
3904 (b'', b'purge', False, _(b'delete queue, and remove patch dir')),
3895 (b'', b'purge', False, _(b'delete queue, and remove patch dir')),
3905 ],
3896 ],
3906 _(b'[OPTION] [QUEUE]'),
3897 _(b'[OPTION] [QUEUE]'),
3907 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3898 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3908 )
3899 )
3909 def qqueue(ui, repo, name=None, **opts):
3900 def qqueue(ui, repo, name=None, **opts):
3910 """manage multiple patch queues
3901 """manage multiple patch queues
3911
3902
3912 Supports switching between different patch queues, as well as creating
3903 Supports switching between different patch queues, as well as creating
3913 new patch queues and deleting existing ones.
3904 new patch queues and deleting existing ones.
3914
3905
3915 Omitting a queue name or specifying -l/--list will show you the registered
3906 Omitting a queue name or specifying -l/--list will show you the registered
3916 queues - by default the "normal" patches queue is registered. The currently
3907 queues - by default the "normal" patches queue is registered. The currently
3917 active queue will be marked with "(active)". Specifying --active will print
3908 active queue will be marked with "(active)". Specifying --active will print
3918 only the name of the active queue.
3909 only the name of the active queue.
3919
3910
3920 To create a new queue, use -c/--create. The queue is automatically made
3911 To create a new queue, use -c/--create. The queue is automatically made
3921 active, except in the case where there are applied patches from the
3912 active, except in the case where there are applied patches from the
3922 currently active queue in the repository. Then the queue will only be
3913 currently active queue in the repository. Then the queue will only be
3923 created and switching will fail.
3914 created and switching will fail.
3924
3915
3925 To delete an existing queue, use --delete. You cannot delete the currently
3916 To delete an existing queue, use --delete. You cannot delete the currently
3926 active queue.
3917 active queue.
3927
3918
3928 Returns 0 on success.
3919 Returns 0 on success.
3929 """
3920 """
3930 q = repo.mq
3921 q = repo.mq
3931 _defaultqueue = b'patches'
3922 _defaultqueue = b'patches'
3932 _allqueues = b'patches.queues'
3923 _allqueues = b'patches.queues'
3933 _activequeue = b'patches.queue'
3924 _activequeue = b'patches.queue'
3934
3925
3935 def _getcurrent():
3926 def _getcurrent():
3936 cur = os.path.basename(q.path)
3927 cur = os.path.basename(q.path)
3937 if cur.startswith(b'patches-'):
3928 if cur.startswith(b'patches-'):
3938 cur = cur[8:]
3929 cur = cur[8:]
3939 return cur
3930 return cur
3940
3931
3941 def _noqueues():
3932 def _noqueues():
3942 try:
3933 try:
3943 fh = repo.vfs(_allqueues, b'r')
3934 fh = repo.vfs(_allqueues, b'r')
3944 fh.close()
3935 fh.close()
3945 except IOError:
3936 except IOError:
3946 return True
3937 return True
3947
3938
3948 return False
3939 return False
3949
3940
3950 def _getqueues():
3941 def _getqueues():
3951 current = _getcurrent()
3942 current = _getcurrent()
3952
3943
3953 try:
3944 try:
3954 fh = repo.vfs(_allqueues, b'r')
3945 fh = repo.vfs(_allqueues, b'r')
3955 queues = [queue.strip() for queue in fh if queue.strip()]
3946 queues = [queue.strip() for queue in fh if queue.strip()]
3956 fh.close()
3947 fh.close()
3957 if current not in queues:
3948 if current not in queues:
3958 queues.append(current)
3949 queues.append(current)
3959 except IOError:
3950 except IOError:
3960 queues = [_defaultqueue]
3951 queues = [_defaultqueue]
3961
3952
3962 return sorted(queues)
3953 return sorted(queues)
3963
3954
3964 def _setactive(name):
3955 def _setactive(name):
3965 if q.applied:
3956 if q.applied:
3966 raise error.Abort(
3957 raise error.Abort(
3967 _(
3958 _(
3968 b'new queue created, but cannot make active '
3959 b'new queue created, but cannot make active '
3969 b'as patches are applied'
3960 b'as patches are applied'
3970 )
3961 )
3971 )
3962 )
3972 _setactivenocheck(name)
3963 _setactivenocheck(name)
3973
3964
3974 def _setactivenocheck(name):
3965 def _setactivenocheck(name):
3975 fh = repo.vfs(_activequeue, b'w')
3966 fh = repo.vfs(_activequeue, b'w')
3976 if name != b'patches':
3967 if name != b'patches':
3977 fh.write(name)
3968 fh.write(name)
3978 fh.close()
3969 fh.close()
3979
3970
3980 def _addqueue(name):
3971 def _addqueue(name):
3981 fh = repo.vfs(_allqueues, b'a')
3972 fh = repo.vfs(_allqueues, b'a')
3982 fh.write(b'%s\n' % (name,))
3973 fh.write(b'%s\n' % (name,))
3983 fh.close()
3974 fh.close()
3984
3975
3985 def _queuedir(name):
3976 def _queuedir(name):
3986 if name == b'patches':
3977 if name == b'patches':
3987 return repo.vfs.join(b'patches')
3978 return repo.vfs.join(b'patches')
3988 else:
3979 else:
3989 return repo.vfs.join(b'patches-' + name)
3980 return repo.vfs.join(b'patches-' + name)
3990
3981
3991 def _validname(name):
3982 def _validname(name):
3992 for n in name:
3983 for n in name:
3993 if n in b':\\/.':
3984 if n in b':\\/.':
3994 return False
3985 return False
3995 return True
3986 return True
3996
3987
3997 def _delete(name):
3988 def _delete(name):
3998 if name not in existing:
3989 if name not in existing:
3999 raise error.Abort(_(b'cannot delete queue that does not exist'))
3990 raise error.Abort(_(b'cannot delete queue that does not exist'))
4000
3991
4001 current = _getcurrent()
3992 current = _getcurrent()
4002
3993
4003 if name == current:
3994 if name == current:
4004 raise error.Abort(_(b'cannot delete currently active queue'))
3995 raise error.Abort(_(b'cannot delete currently active queue'))
4005
3996
4006 fh = repo.vfs(b'patches.queues.new', b'w')
3997 fh = repo.vfs(b'patches.queues.new', b'w')
4007 for queue in existing:
3998 for queue in existing:
4008 if queue == name:
3999 if queue == name:
4009 continue
4000 continue
4010 fh.write(b'%s\n' % (queue,))
4001 fh.write(b'%s\n' % (queue,))
4011 fh.close()
4002 fh.close()
4012 repo.vfs.rename(b'patches.queues.new', _allqueues)
4003 repo.vfs.rename(b'patches.queues.new', _allqueues)
4013
4004
4014 opts = pycompat.byteskwargs(opts)
4005 opts = pycompat.byteskwargs(opts)
4015 if not name or opts.get(b'list') or opts.get(b'active'):
4006 if not name or opts.get(b'list') or opts.get(b'active'):
4016 current = _getcurrent()
4007 current = _getcurrent()
4017 if opts.get(b'active'):
4008 if opts.get(b'active'):
4018 ui.write(b'%s\n' % (current,))
4009 ui.write(b'%s\n' % (current,))
4019 return
4010 return
4020 for queue in _getqueues():
4011 for queue in _getqueues():
4021 ui.write(b'%s' % (queue,))
4012 ui.write(b'%s' % (queue,))
4022 if queue == current and not ui.quiet:
4013 if queue == current and not ui.quiet:
4023 ui.write(_(b' (active)\n'))
4014 ui.write(_(b' (active)\n'))
4024 else:
4015 else:
4025 ui.write(b'\n')
4016 ui.write(b'\n')
4026 return
4017 return
4027
4018
4028 if not _validname(name):
4019 if not _validname(name):
4029 raise error.Abort(
4020 raise error.Abort(
4030 _(b'invalid queue name, may not contain the characters ":\\/."')
4021 _(b'invalid queue name, may not contain the characters ":\\/."')
4031 )
4022 )
4032
4023
4033 with repo.wlock():
4024 with repo.wlock():
4034 existing = _getqueues()
4025 existing = _getqueues()
4035
4026
4036 if opts.get(b'create'):
4027 if opts.get(b'create'):
4037 if name in existing:
4028 if name in existing:
4038 raise error.Abort(_(b'queue "%s" already exists') % name)
4029 raise error.Abort(_(b'queue "%s" already exists') % name)
4039 if _noqueues():
4030 if _noqueues():
4040 _addqueue(_defaultqueue)
4031 _addqueue(_defaultqueue)
4041 _addqueue(name)
4032 _addqueue(name)
4042 _setactive(name)
4033 _setactive(name)
4043 elif opts.get(b'rename'):
4034 elif opts.get(b'rename'):
4044 current = _getcurrent()
4035 current = _getcurrent()
4045 if name == current:
4036 if name == current:
4046 raise error.Abort(
4037 raise error.Abort(
4047 _(b'can\'t rename "%s" to its current name') % name
4038 _(b'can\'t rename "%s" to its current name') % name
4048 )
4039 )
4049 if name in existing:
4040 if name in existing:
4050 raise error.Abort(_(b'queue "%s" already exists') % name)
4041 raise error.Abort(_(b'queue "%s" already exists') % name)
4051
4042
4052 olddir = _queuedir(current)
4043 olddir = _queuedir(current)
4053 newdir = _queuedir(name)
4044 newdir = _queuedir(name)
4054
4045
4055 if os.path.exists(newdir):
4046 if os.path.exists(newdir):
4056 raise error.Abort(
4047 raise error.Abort(
4057 _(b'non-queue directory "%s" already exists') % newdir
4048 _(b'non-queue directory "%s" already exists') % newdir
4058 )
4049 )
4059
4050
4060 fh = repo.vfs(b'patches.queues.new', b'w')
4051 fh = repo.vfs(b'patches.queues.new', b'w')
4061 for queue in existing:
4052 for queue in existing:
4062 if queue == current:
4053 if queue == current:
4063 fh.write(b'%s\n' % (name,))
4054 fh.write(b'%s\n' % (name,))
4064 if os.path.exists(olddir):
4055 if os.path.exists(olddir):
4065 util.rename(olddir, newdir)
4056 util.rename(olddir, newdir)
4066 else:
4057 else:
4067 fh.write(b'%s\n' % (queue,))
4058 fh.write(b'%s\n' % (queue,))
4068 fh.close()
4059 fh.close()
4069 repo.vfs.rename(b'patches.queues.new', _allqueues)
4060 repo.vfs.rename(b'patches.queues.new', _allqueues)
4070 _setactivenocheck(name)
4061 _setactivenocheck(name)
4071 elif opts.get(b'delete'):
4062 elif opts.get(b'delete'):
4072 _delete(name)
4063 _delete(name)
4073 elif opts.get(b'purge'):
4064 elif opts.get(b'purge'):
4074 if name in existing:
4065 if name in existing:
4075 _delete(name)
4066 _delete(name)
4076 qdir = _queuedir(name)
4067 qdir = _queuedir(name)
4077 if os.path.exists(qdir):
4068 if os.path.exists(qdir):
4078 shutil.rmtree(qdir)
4069 shutil.rmtree(qdir)
4079 else:
4070 else:
4080 if name not in existing:
4071 if name not in existing:
4081 raise error.Abort(_(b'use --create to create a new queue'))
4072 raise error.Abort(_(b'use --create to create a new queue'))
4082 _setactive(name)
4073 _setactive(name)
4083
4074
4084
4075
4085 def mqphasedefaults(repo, roots):
4076 def mqphasedefaults(repo, roots):
4086 """callback used to set mq changeset as secret when no phase data exists"""
4077 """callback used to set mq changeset as secret when no phase data exists"""
4087 if repo.mq.applied:
4078 if repo.mq.applied:
4088 if repo.ui.configbool(b'mq', b'secret'):
4079 if repo.ui.configbool(b'mq', b'secret'):
4089 mqphase = phases.secret
4080 mqphase = phases.secret
4090 else:
4081 else:
4091 mqphase = phases.draft
4082 mqphase = phases.draft
4092 qbase = repo[repo.mq.applied[0].node]
4083 qbase = repo[repo.mq.applied[0].node]
4093 roots[mqphase].add(qbase.node())
4084 roots[mqphase].add(qbase.node())
4094 return roots
4085 return roots
4095
4086
4096
4087
4097 def reposetup(ui, repo):
4088 def reposetup(ui, repo):
4098 class mqrepo(repo.__class__):
4089 class mqrepo(repo.__class__):
4099 @localrepo.unfilteredpropertycache
4090 @localrepo.unfilteredpropertycache
4100 def mq(self):
4091 def mq(self):
4101 return queue(self.ui, self.baseui, self.path)
4092 return queue(self.ui, self.baseui, self.path)
4102
4093
4103 def invalidateall(self):
4094 def invalidateall(self):
4104 super(mqrepo, self).invalidateall()
4095 super(mqrepo, self).invalidateall()
4105 if localrepo.hasunfilteredcache(self, 'mq'):
4096 if localrepo.hasunfilteredcache(self, 'mq'):
4106 # recreate mq in case queue path was changed
4097 # recreate mq in case queue path was changed
4107 delattr(self.unfiltered(), 'mq')
4098 delattr(self.unfiltered(), 'mq')
4108
4099
4109 def abortifwdirpatched(self, errmsg, force=False):
4100 def abortifwdirpatched(self, errmsg, force=False):
4110 if self.mq.applied and self.mq.checkapplied and not force:
4101 if self.mq.applied and self.mq.checkapplied and not force:
4111 parents = self.dirstate.parents()
4102 parents = self.dirstate.parents()
4112 patches = [s.node for s in self.mq.applied]
4103 patches = [s.node for s in self.mq.applied]
4113 if any(p in patches for p in parents):
4104 if any(p in patches for p in parents):
4114 raise error.Abort(errmsg)
4105 raise error.Abort(errmsg)
4115
4106
4116 def commit(
4107 def commit(
4117 self,
4108 self,
4118 text=b"",
4109 text=b"",
4119 user=None,
4110 user=None,
4120 date=None,
4111 date=None,
4121 match=None,
4112 match=None,
4122 force=False,
4113 force=False,
4123 editor=False,
4114 editor=False,
4124 extra=None,
4115 extra=None,
4125 ):
4116 ):
4126 if extra is None:
4117 if extra is None:
4127 extra = {}
4118 extra = {}
4128 self.abortifwdirpatched(
4119 self.abortifwdirpatched(
4129 _(b'cannot commit over an applied mq patch'), force
4120 _(b'cannot commit over an applied mq patch'), force
4130 )
4121 )
4131
4122
4132 return super(mqrepo, self).commit(
4123 return super(mqrepo, self).commit(
4133 text, user, date, match, force, editor, extra
4124 text, user, date, match, force, editor, extra
4134 )
4125 )
4135
4126
4136 def checkpush(self, pushop):
4127 def checkpush(self, pushop):
4137 if self.mq.applied and self.mq.checkapplied and not pushop.force:
4128 if self.mq.applied and self.mq.checkapplied and not pushop.force:
4138 outapplied = [e.node for e in self.mq.applied]
4129 outapplied = [e.node for e in self.mq.applied]
4139 if pushop.revs:
4130 if pushop.revs:
4140 # Assume applied patches have no non-patch descendants and
4131 # Assume applied patches have no non-patch descendants and
4141 # are not on remote already. Filtering any changeset not
4132 # are not on remote already. Filtering any changeset not
4142 # pushed.
4133 # pushed.
4143 heads = set(pushop.revs)
4134 heads = set(pushop.revs)
4144 for node in reversed(outapplied):
4135 for node in reversed(outapplied):
4145 if node in heads:
4136 if node in heads:
4146 break
4137 break
4147 else:
4138 else:
4148 outapplied.pop()
4139 outapplied.pop()
4149 # looking for pushed and shared changeset
4140 # looking for pushed and shared changeset
4150 for node in outapplied:
4141 for node in outapplied:
4151 if self[node].phase() < phases.secret:
4142 if self[node].phase() < phases.secret:
4152 raise error.Abort(_(b'source has mq patches applied'))
4143 raise error.Abort(_(b'source has mq patches applied'))
4153 # no non-secret patches pushed
4144 # no non-secret patches pushed
4154 super(mqrepo, self).checkpush(pushop)
4145 super(mqrepo, self).checkpush(pushop)
4155
4146
4156 def _findtags(self):
4147 def _findtags(self):
4157 '''augment tags from base class with patch tags'''
4148 '''augment tags from base class with patch tags'''
4158 result = super(mqrepo, self)._findtags()
4149 result = super(mqrepo, self)._findtags()
4159
4150
4160 q = self.mq
4151 q = self.mq
4161 if not q.applied:
4152 if not q.applied:
4162 return result
4153 return result
4163
4154
4164 mqtags = [(patch.node, patch.name) for patch in q.applied]
4155 mqtags = [(patch.node, patch.name) for patch in q.applied]
4165
4156
4166 try:
4157 try:
4167 # for now ignore filtering business
4158 # for now ignore filtering business
4168 self.unfiltered().changelog.rev(mqtags[-1][0])
4159 self.unfiltered().changelog.rev(mqtags[-1][0])
4169 except error.LookupError:
4160 except error.LookupError:
4170 self.ui.warn(
4161 self.ui.warn(
4171 _(b'mq status file refers to unknown node %s\n')
4162 _(b'mq status file refers to unknown node %s\n')
4172 % short(mqtags[-1][0])
4163 % short(mqtags[-1][0])
4173 )
4164 )
4174 return result
4165 return result
4175
4166
4176 # do not add fake tags for filtered revisions
4167 # do not add fake tags for filtered revisions
4177 included = self.changelog.hasnode
4168 included = self.changelog.hasnode
4178 mqtags = [mqt for mqt in mqtags if included(mqt[0])]
4169 mqtags = [mqt for mqt in mqtags if included(mqt[0])]
4179 if not mqtags:
4170 if not mqtags:
4180 return result
4171 return result
4181
4172
4182 mqtags.append((mqtags[-1][0], b'qtip'))
4173 mqtags.append((mqtags[-1][0], b'qtip'))
4183 mqtags.append((mqtags[0][0], b'qbase'))
4174 mqtags.append((mqtags[0][0], b'qbase'))
4184 mqtags.append((self.changelog.parents(mqtags[0][0])[0], b'qparent'))
4175 mqtags.append((self.changelog.parents(mqtags[0][0])[0], b'qparent'))
4185 tags = result[0]
4176 tags = result[0]
4186 for patch in mqtags:
4177 for patch in mqtags:
4187 if patch[1] in tags:
4178 if patch[1] in tags:
4188 self.ui.warn(
4179 self.ui.warn(
4189 _(b'tag %s overrides mq patch of the same name\n')
4180 _(b'tag %s overrides mq patch of the same name\n')
4190 % patch[1]
4181 % patch[1]
4191 )
4182 )
4192 else:
4183 else:
4193 tags[patch[1]] = patch[0]
4184 tags[patch[1]] = patch[0]
4194
4185
4195 return result
4186 return result
4196
4187
4197 if repo.local():
4188 if repo.local():
4198 repo.__class__ = mqrepo
4189 repo.__class__ = mqrepo
4199
4190
4200 repo._phasedefaults.append(mqphasedefaults)
4191 repo._phasedefaults.append(mqphasedefaults)
4201
4192
4202
4193
4203 def mqimport(orig, ui, repo, *args, **kwargs):
4194 def mqimport(orig, ui, repo, *args, **kwargs):
4204 if util.safehasattr(repo, b'abortifwdirpatched') and not kwargs.get(
4195 if util.safehasattr(repo, b'abortifwdirpatched') and not kwargs.get(
4205 'no_commit', False
4196 'no_commit', False
4206 ):
4197 ):
4207 repo.abortifwdirpatched(
4198 repo.abortifwdirpatched(
4208 _(b'cannot import over an applied patch'), kwargs.get('force')
4199 _(b'cannot import over an applied patch'), kwargs.get('force')
4209 )
4200 )
4210 return orig(ui, repo, *args, **kwargs)
4201 return orig(ui, repo, *args, **kwargs)
4211
4202
4212
4203
4213 def mqinit(orig, ui, *args, **kwargs):
4204 def mqinit(orig, ui, *args, **kwargs):
4214 mq = kwargs.pop('mq', None)
4205 mq = kwargs.pop('mq', None)
4215
4206
4216 if not mq:
4207 if not mq:
4217 return orig(ui, *args, **kwargs)
4208 return orig(ui, *args, **kwargs)
4218
4209
4219 if args:
4210 if args:
4220 repopath = args[0]
4211 repopath = args[0]
4221 if not hg.islocal(repopath):
4212 if not hg.islocal(repopath):
4222 raise error.Abort(
4213 raise error.Abort(
4223 _(b'only a local queue repository may be initialized')
4214 _(b'only a local queue repository may be initialized')
4224 )
4215 )
4225 else:
4216 else:
4226 repopath = cmdutil.findrepo(encoding.getcwd())
4217 repopath = cmdutil.findrepo(encoding.getcwd())
4227 if not repopath:
4218 if not repopath:
4228 raise error.Abort(
4219 raise error.Abort(
4229 _(b'there is no Mercurial repository here (.hg not found)')
4220 _(b'there is no Mercurial repository here (.hg not found)')
4230 )
4221 )
4231 repo = hg.repository(ui, repopath)
4222 repo = hg.repository(ui, repopath)
4232 return qinit(ui, repo, True)
4223 return qinit(ui, repo, True)
4233
4224
4234
4225
4235 def mqcommand(orig, ui, repo, *args, **kwargs):
4226 def mqcommand(orig, ui, repo, *args, **kwargs):
4236 """Add --mq option to operate on patch repository instead of main"""
4227 """Add --mq option to operate on patch repository instead of main"""
4237
4228
4238 # some commands do not like getting unknown options
4229 # some commands do not like getting unknown options
4239 mq = kwargs.pop('mq', None)
4230 mq = kwargs.pop('mq', None)
4240
4231
4241 if not mq:
4232 if not mq:
4242 return orig(ui, repo, *args, **kwargs)
4233 return orig(ui, repo, *args, **kwargs)
4243
4234
4244 q = repo.mq
4235 q = repo.mq
4245 r = q.qrepo()
4236 r = q.qrepo()
4246 if not r:
4237 if not r:
4247 raise error.Abort(_(b'no queue repository'))
4238 raise error.Abort(_(b'no queue repository'))
4248 return orig(r.ui, r, *args, **kwargs)
4239 return orig(r.ui, r, *args, **kwargs)
4249
4240
4250
4241
4251 def summaryhook(ui, repo):
4242 def summaryhook(ui, repo):
4252 q = repo.mq
4243 q = repo.mq
4253 m = []
4244 m = []
4254 a, u = len(q.applied), len(q.unapplied(repo))
4245 a, u = len(q.applied), len(q.unapplied(repo))
4255 if a:
4246 if a:
4256 m.append(ui.label(_(b"%d applied"), b'qseries.applied') % a)
4247 m.append(ui.label(_(b"%d applied"), b'qseries.applied') % a)
4257 if u:
4248 if u:
4258 m.append(ui.label(_(b"%d unapplied"), b'qseries.unapplied') % u)
4249 m.append(ui.label(_(b"%d unapplied"), b'qseries.unapplied') % u)
4259 if m:
4250 if m:
4260 # i18n: column positioning for "hg summary"
4251 # i18n: column positioning for "hg summary"
4261 ui.write(_(b"mq: %s\n") % b', '.join(m))
4252 ui.write(_(b"mq: %s\n") % b', '.join(m))
4262 else:
4253 else:
4263 # i18n: column positioning for "hg summary"
4254 # i18n: column positioning for "hg summary"
4264 ui.note(_(b"mq: (empty queue)\n"))
4255 ui.note(_(b"mq: (empty queue)\n"))
4265
4256
4266
4257
4267 revsetpredicate = registrar.revsetpredicate()
4258 revsetpredicate = registrar.revsetpredicate()
4268
4259
4269
4260
4270 @revsetpredicate(b'mq()')
4261 @revsetpredicate(b'mq()')
4271 def revsetmq(repo, subset, x):
4262 def revsetmq(repo, subset, x):
4272 """Changesets managed by MQ."""
4263 """Changesets managed by MQ."""
4273 revsetlang.getargs(x, 0, 0, _(b"mq takes no arguments"))
4264 revsetlang.getargs(x, 0, 0, _(b"mq takes no arguments"))
4274 applied = {repo[r.node].rev() for r in repo.mq.applied}
4265 applied = {repo[r.node].rev() for r in repo.mq.applied}
4275 return smartset.baseset([r for r in subset if r in applied])
4266 return smartset.baseset([r for r in subset if r in applied])
4276
4267
4277
4268
4278 # tell hggettext to extract docstrings from these functions:
4269 # tell hggettext to extract docstrings from these functions:
4279 i18nfunctions = [revsetmq]
4270 i18nfunctions = [revsetmq]
4280
4271
4281
4272
4282 def extsetup(ui):
4273 def extsetup(ui):
4283 # Ensure mq wrappers are called first, regardless of extension load order by
4274 # Ensure mq wrappers are called first, regardless of extension load order by
4284 # NOT wrapping in uisetup() and instead deferring to init stage two here.
4275 # NOT wrapping in uisetup() and instead deferring to init stage two here.
4285 mqopt = [(b'', b'mq', None, _(b"operate on patch repository"))]
4276 mqopt = [(b'', b'mq', None, _(b"operate on patch repository"))]
4286
4277
4287 extensions.wrapcommand(commands.table, b'import', mqimport)
4278 extensions.wrapcommand(commands.table, b'import', mqimport)
4288 cmdutil.summaryhooks.add(b'mq', summaryhook)
4279 cmdutil.summaryhooks.add(b'mq', summaryhook)
4289
4280
4290 entry = extensions.wrapcommand(commands.table, b'init', mqinit)
4281 entry = extensions.wrapcommand(commands.table, b'init', mqinit)
4291 entry[1].extend(mqopt)
4282 entry[1].extend(mqopt)
4292
4283
4293 def dotable(cmdtable):
4284 def dotable(cmdtable):
4294 for cmd, entry in pycompat.iteritems(cmdtable):
4285 for cmd, entry in pycompat.iteritems(cmdtable):
4295 cmd = cmdutil.parsealiases(cmd)[0]
4286 cmd = cmdutil.parsealiases(cmd)[0]
4296 func = entry[0]
4287 func = entry[0]
4297 if func.norepo:
4288 if func.norepo:
4298 continue
4289 continue
4299 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
4290 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
4300 entry[1].extend(mqopt)
4291 entry[1].extend(mqopt)
4301
4292
4302 dotable(commands.table)
4293 dotable(commands.table)
4303
4294
4304 thismodule = sys.modules["hgext.mq"]
4295 thismodule = sys.modules["hgext.mq"]
4305 for extname, extmodule in extensions.extensions():
4296 for extname, extmodule in extensions.extensions():
4306 if extmodule != thismodule:
4297 if extmodule != thismodule:
4307 dotable(getattr(extmodule, 'cmdtable', {}))
4298 dotable(getattr(extmodule, 'cmdtable', {}))
4308
4299
4309
4300
4310 colortable = {
4301 colortable = {
4311 b'qguard.negative': b'red',
4302 b'qguard.negative': b'red',
4312 b'qguard.positive': b'yellow',
4303 b'qguard.positive': b'yellow',
4313 b'qguard.unguarded': b'green',
4304 b'qguard.unguarded': b'green',
4314 b'qseries.applied': b'blue bold underline',
4305 b'qseries.applied': b'blue bold underline',
4315 b'qseries.guarded': b'black bold',
4306 b'qseries.guarded': b'black bold',
4316 b'qseries.missing': b'red bold',
4307 b'qseries.missing': b'red bold',
4317 b'qseries.unapplied': b'black bold',
4308 b'qseries.unapplied': b'black bold',
4318 }
4309 }
General Comments 0
You need to be logged in to leave comments. Login now