##// END OF EJS Templates
mq: replace usage of `normal` with newer API...
marmoute -
r48517:d905eff4 default
parent child Browse files
Show More
@@ -1,4316 +1,4318 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 = []
1093 removed = []
1094 merged = []
1094 merged = []
1095 for f in files:
1095 for f in files:
1096 if os.path.lexists(repo.wjoin(f)):
1096 if os.path.lexists(repo.wjoin(f)):
1097 merged.append(f)
1097 merged.append(f)
1098 else:
1098 else:
1099 removed.append(f)
1099 removed.append(f)
1100 with repo.dirstate.parentchange():
1100 with repo.dirstate.parentchange():
1101 for f in removed:
1101 for f in removed:
1102 repo.dirstate.update_file_p1(f, p1_tracked=True)
1102 repo.dirstate.update_file_p1(f, p1_tracked=True)
1103 for f in merged:
1103 for f in merged:
1104 repo.dirstate.merge(f)
1104 repo.dirstate.merge(f)
1105 p1 = repo.dirstate.p1()
1105 p1 = repo.dirstate.p1()
1106 repo.setparents(p1, merge)
1106 repo.setparents(p1, merge)
1107
1107
1108 if all_files and b'.hgsubstate' in all_files:
1108 if all_files and b'.hgsubstate' in all_files:
1109 wctx = repo[None]
1109 wctx = repo[None]
1110 pctx = repo[b'.']
1110 pctx = repo[b'.']
1111 overwrite = False
1111 overwrite = False
1112 mergedsubstate = subrepoutil.submerge(
1112 mergedsubstate = subrepoutil.submerge(
1113 repo, pctx, wctx, wctx, overwrite
1113 repo, pctx, wctx, wctx, overwrite
1114 )
1114 )
1115 files += mergedsubstate.keys()
1115 files += mergedsubstate.keys()
1116
1116
1117 match = scmutil.matchfiles(repo, files or [])
1117 match = scmutil.matchfiles(repo, files or [])
1118 oldtip = repo.changelog.tip()
1118 oldtip = repo.changelog.tip()
1119 n = newcommit(
1119 n = newcommit(
1120 repo, None, message, ph.user, ph.date, match=match, force=True
1120 repo, None, message, ph.user, ph.date, match=match, force=True
1121 )
1121 )
1122 if repo.changelog.tip() == oldtip:
1122 if repo.changelog.tip() == oldtip:
1123 raise error.Abort(
1123 raise error.Abort(
1124 _(b"qpush exactly duplicates child changeset")
1124 _(b"qpush exactly duplicates child changeset")
1125 )
1125 )
1126 if n is None:
1126 if n is None:
1127 raise error.Abort(_(b"repository commit failed"))
1127 raise error.Abort(_(b"repository commit failed"))
1128
1128
1129 if update_status:
1129 if update_status:
1130 self.applied.append(statusentry(n, patchname))
1130 self.applied.append(statusentry(n, patchname))
1131
1131
1132 if patcherr:
1132 if patcherr:
1133 self.ui.warn(
1133 self.ui.warn(
1134 _(b"patch failed, rejects left in working directory\n")
1134 _(b"patch failed, rejects left in working directory\n")
1135 )
1135 )
1136 err = 2
1136 err = 2
1137 break
1137 break
1138
1138
1139 if fuzz and strict:
1139 if fuzz and strict:
1140 self.ui.warn(_(b"fuzz found when applying patch, stopping\n"))
1140 self.ui.warn(_(b"fuzz found when applying patch, stopping\n"))
1141 err = 3
1141 err = 3
1142 break
1142 break
1143 return (err, n)
1143 return (err, n)
1144
1144
1145 def _cleanup(self, patches, numrevs, keep=False):
1145 def _cleanup(self, patches, numrevs, keep=False):
1146 if not keep:
1146 if not keep:
1147 r = self.qrepo()
1147 r = self.qrepo()
1148 if r:
1148 if r:
1149 r[None].forget(patches)
1149 r[None].forget(patches)
1150 for p in patches:
1150 for p in patches:
1151 try:
1151 try:
1152 os.unlink(self.join(p))
1152 os.unlink(self.join(p))
1153 except OSError as inst:
1153 except OSError as inst:
1154 if inst.errno != errno.ENOENT:
1154 if inst.errno != errno.ENOENT:
1155 raise
1155 raise
1156
1156
1157 qfinished = []
1157 qfinished = []
1158 if numrevs:
1158 if numrevs:
1159 qfinished = self.applied[:numrevs]
1159 qfinished = self.applied[:numrevs]
1160 del self.applied[:numrevs]
1160 del self.applied[:numrevs]
1161 self.applieddirty = True
1161 self.applieddirty = True
1162
1162
1163 unknown = []
1163 unknown = []
1164
1164
1165 sortedseries = []
1165 sortedseries = []
1166 for p in patches:
1166 for p in patches:
1167 idx = self.findseries(p)
1167 idx = self.findseries(p)
1168 if idx is None:
1168 if idx is None:
1169 sortedseries.append((-1, p))
1169 sortedseries.append((-1, p))
1170 else:
1170 else:
1171 sortedseries.append((idx, p))
1171 sortedseries.append((idx, p))
1172
1172
1173 sortedseries.sort(reverse=True)
1173 sortedseries.sort(reverse=True)
1174 for (i, p) in sortedseries:
1174 for (i, p) in sortedseries:
1175 if i != -1:
1175 if i != -1:
1176 del self.fullseries[i]
1176 del self.fullseries[i]
1177 else:
1177 else:
1178 unknown.append(p)
1178 unknown.append(p)
1179
1179
1180 if unknown:
1180 if unknown:
1181 if numrevs:
1181 if numrevs:
1182 rev = {entry.name: entry.node for entry in qfinished}
1182 rev = {entry.name: entry.node for entry in qfinished}
1183 for p in unknown:
1183 for p in unknown:
1184 msg = _(b'revision %s refers to unknown patches: %s\n')
1184 msg = _(b'revision %s refers to unknown patches: %s\n')
1185 self.ui.warn(msg % (short(rev[p]), p))
1185 self.ui.warn(msg % (short(rev[p]), p))
1186 else:
1186 else:
1187 msg = _(b'unknown patches: %s\n')
1187 msg = _(b'unknown patches: %s\n')
1188 raise error.Abort(b''.join(msg % p for p in unknown))
1188 raise error.Abort(b''.join(msg % p for p in unknown))
1189
1189
1190 self.parseseries()
1190 self.parseseries()
1191 self.seriesdirty = True
1191 self.seriesdirty = True
1192 return [entry.node for entry in qfinished]
1192 return [entry.node for entry in qfinished]
1193
1193
1194 def _revpatches(self, repo, revs):
1194 def _revpatches(self, repo, revs):
1195 firstrev = repo[self.applied[0].node].rev()
1195 firstrev = repo[self.applied[0].node].rev()
1196 patches = []
1196 patches = []
1197 for i, rev in enumerate(revs):
1197 for i, rev in enumerate(revs):
1198
1198
1199 if rev < firstrev:
1199 if rev < firstrev:
1200 raise error.Abort(_(b'revision %d is not managed') % rev)
1200 raise error.Abort(_(b'revision %d is not managed') % rev)
1201
1201
1202 ctx = repo[rev]
1202 ctx = repo[rev]
1203 base = self.applied[i].node
1203 base = self.applied[i].node
1204 if ctx.node() != base:
1204 if ctx.node() != base:
1205 msg = _(b'cannot delete revision %d above applied patches')
1205 msg = _(b'cannot delete revision %d above applied patches')
1206 raise error.Abort(msg % rev)
1206 raise error.Abort(msg % rev)
1207
1207
1208 patch = self.applied[i].name
1208 patch = self.applied[i].name
1209 for fmt in (b'[mq]: %s', b'imported patch %s'):
1209 for fmt in (b'[mq]: %s', b'imported patch %s'):
1210 if ctx.description() == fmt % patch:
1210 if ctx.description() == fmt % patch:
1211 msg = _(b'patch %s finalized without changeset message\n')
1211 msg = _(b'patch %s finalized without changeset message\n')
1212 repo.ui.status(msg % patch)
1212 repo.ui.status(msg % patch)
1213 break
1213 break
1214
1214
1215 patches.append(patch)
1215 patches.append(patch)
1216 return patches
1216 return patches
1217
1217
1218 def finish(self, repo, revs):
1218 def finish(self, repo, revs):
1219 # Manually trigger phase computation to ensure phasedefaults is
1219 # Manually trigger phase computation to ensure phasedefaults is
1220 # executed before we remove the patches.
1220 # executed before we remove the patches.
1221 repo._phasecache
1221 repo._phasecache
1222 patches = self._revpatches(repo, sorted(revs))
1222 patches = self._revpatches(repo, sorted(revs))
1223 qfinished = self._cleanup(patches, len(patches))
1223 qfinished = self._cleanup(patches, len(patches))
1224 if qfinished and repo.ui.configbool(b'mq', b'secret'):
1224 if qfinished and repo.ui.configbool(b'mq', b'secret'):
1225 # only use this logic when the secret option is added
1225 # only use this logic when the secret option is added
1226 oldqbase = repo[qfinished[0]]
1226 oldqbase = repo[qfinished[0]]
1227 tphase = phases.newcommitphase(repo.ui)
1227 tphase = phases.newcommitphase(repo.ui)
1228 if oldqbase.phase() > tphase and oldqbase.p1().phase() <= tphase:
1228 if oldqbase.phase() > tphase and oldqbase.p1().phase() <= tphase:
1229 with repo.transaction(b'qfinish') as tr:
1229 with repo.transaction(b'qfinish') as tr:
1230 phases.advanceboundary(repo, tr, tphase, qfinished)
1230 phases.advanceboundary(repo, tr, tphase, qfinished)
1231
1231
1232 def delete(self, repo, patches, opts):
1232 def delete(self, repo, patches, opts):
1233 if not patches and not opts.get(b'rev'):
1233 if not patches and not opts.get(b'rev'):
1234 raise error.Abort(
1234 raise error.Abort(
1235 _(b'qdelete requires at least one revision or patch name')
1235 _(b'qdelete requires at least one revision or patch name')
1236 )
1236 )
1237
1237
1238 realpatches = []
1238 realpatches = []
1239 for patch in patches:
1239 for patch in patches:
1240 patch = self.lookup(patch, strict=True)
1240 patch = self.lookup(patch, strict=True)
1241 info = self.isapplied(patch)
1241 info = self.isapplied(patch)
1242 if info:
1242 if info:
1243 raise error.Abort(_(b"cannot delete applied patch %s") % patch)
1243 raise error.Abort(_(b"cannot delete applied patch %s") % patch)
1244 if patch not in self.series:
1244 if patch not in self.series:
1245 raise error.Abort(_(b"patch %s not in series file") % patch)
1245 raise error.Abort(_(b"patch %s not in series file") % patch)
1246 if patch not in realpatches:
1246 if patch not in realpatches:
1247 realpatches.append(patch)
1247 realpatches.append(patch)
1248
1248
1249 numrevs = 0
1249 numrevs = 0
1250 if opts.get(b'rev'):
1250 if opts.get(b'rev'):
1251 if not self.applied:
1251 if not self.applied:
1252 raise error.Abort(_(b'no patches applied'))
1252 raise error.Abort(_(b'no patches applied'))
1253 revs = scmutil.revrange(repo, opts.get(b'rev'))
1253 revs = scmutil.revrange(repo, opts.get(b'rev'))
1254 revs.sort()
1254 revs.sort()
1255 revpatches = self._revpatches(repo, revs)
1255 revpatches = self._revpatches(repo, revs)
1256 realpatches += revpatches
1256 realpatches += revpatches
1257 numrevs = len(revpatches)
1257 numrevs = len(revpatches)
1258
1258
1259 self._cleanup(realpatches, numrevs, opts.get(b'keep'))
1259 self._cleanup(realpatches, numrevs, opts.get(b'keep'))
1260
1260
1261 def checktoppatch(self, repo):
1261 def checktoppatch(self, repo):
1262 '''check that working directory is at qtip'''
1262 '''check that working directory is at qtip'''
1263 if self.applied:
1263 if self.applied:
1264 top = self.applied[-1].node
1264 top = self.applied[-1].node
1265 patch = self.applied[-1].name
1265 patch = self.applied[-1].name
1266 if repo.dirstate.p1() != top:
1266 if repo.dirstate.p1() != top:
1267 raise error.Abort(_(b"working directory revision is not qtip"))
1267 raise error.Abort(_(b"working directory revision is not qtip"))
1268 return top, patch
1268 return top, patch
1269 return None, None
1269 return None, None
1270
1270
1271 def putsubstate2changes(self, substatestate, changes):
1271 def putsubstate2changes(self, substatestate, changes):
1272 if isinstance(changes, list):
1272 if isinstance(changes, list):
1273 mar = changes[:3]
1273 mar = changes[:3]
1274 else:
1274 else:
1275 mar = (changes.modified, changes.added, changes.removed)
1275 mar = (changes.modified, changes.added, changes.removed)
1276 if any((b'.hgsubstate' in files for files in mar)):
1276 if any((b'.hgsubstate' in files for files in mar)):
1277 return # already listed up
1277 return # already listed up
1278 # not yet listed up
1278 # not yet listed up
1279 if substatestate in b'a?':
1279 if substatestate in b'a?':
1280 mar[1].append(b'.hgsubstate')
1280 mar[1].append(b'.hgsubstate')
1281 elif substatestate in b'r':
1281 elif substatestate in b'r':
1282 mar[2].append(b'.hgsubstate')
1282 mar[2].append(b'.hgsubstate')
1283 else: # modified
1283 else: # modified
1284 mar[0].append(b'.hgsubstate')
1284 mar[0].append(b'.hgsubstate')
1285
1285
1286 def checklocalchanges(self, repo, force=False, refresh=True):
1286 def checklocalchanges(self, repo, force=False, refresh=True):
1287 excsuffix = b''
1287 excsuffix = b''
1288 if refresh:
1288 if refresh:
1289 excsuffix = b', qrefresh first'
1289 excsuffix = b', qrefresh first'
1290 # plain versions for i18n tool to detect them
1290 # plain versions for i18n tool to detect them
1291 _(b"local changes found, qrefresh first")
1291 _(b"local changes found, qrefresh first")
1292 _(b"local changed subrepos found, qrefresh first")
1292 _(b"local changed subrepos found, qrefresh first")
1293
1293
1294 s = repo.status()
1294 s = repo.status()
1295 if not force:
1295 if not force:
1296 cmdutil.checkunfinished(repo)
1296 cmdutil.checkunfinished(repo)
1297 if s.modified or s.added or s.removed or s.deleted:
1297 if s.modified or s.added or s.removed or s.deleted:
1298 _(b"local changes found") # i18n tool detection
1298 _(b"local changes found") # i18n tool detection
1299 raise error.Abort(_(b"local changes found" + excsuffix))
1299 raise error.Abort(_(b"local changes found" + excsuffix))
1300 if checksubstate(repo):
1300 if checksubstate(repo):
1301 _(b"local changed subrepos found") # i18n tool detection
1301 _(b"local changed subrepos found") # i18n tool detection
1302 raise error.Abort(
1302 raise error.Abort(
1303 _(b"local changed subrepos found" + excsuffix)
1303 _(b"local changed subrepos found" + excsuffix)
1304 )
1304 )
1305 else:
1305 else:
1306 cmdutil.checkunfinished(repo, skipmerge=True)
1306 cmdutil.checkunfinished(repo, skipmerge=True)
1307 return s
1307 return s
1308
1308
1309 _reserved = (b'series', b'status', b'guards', b'.', b'..')
1309 _reserved = (b'series', b'status', b'guards', b'.', b'..')
1310
1310
1311 def checkreservedname(self, name):
1311 def checkreservedname(self, name):
1312 if name in self._reserved:
1312 if name in self._reserved:
1313 raise error.Abort(
1313 raise error.Abort(
1314 _(b'"%s" cannot be used as the name of a patch') % name
1314 _(b'"%s" cannot be used as the name of a patch') % name
1315 )
1315 )
1316 if name != name.strip():
1316 if name != name.strip():
1317 # whitespace is stripped by parseseries()
1317 # whitespace is stripped by parseseries()
1318 raise error.Abort(
1318 raise error.Abort(
1319 _(b'patch name cannot begin or end with whitespace')
1319 _(b'patch name cannot begin or end with whitespace')
1320 )
1320 )
1321 for prefix in (b'.hg', b'.mq'):
1321 for prefix in (b'.hg', b'.mq'):
1322 if name.startswith(prefix):
1322 if name.startswith(prefix):
1323 raise error.Abort(
1323 raise error.Abort(
1324 _(b'patch name cannot begin with "%s"') % prefix
1324 _(b'patch name cannot begin with "%s"') % prefix
1325 )
1325 )
1326 for c in (b'#', b':', b'\r', b'\n'):
1326 for c in (b'#', b':', b'\r', b'\n'):
1327 if c in name:
1327 if c in name:
1328 raise error.Abort(
1328 raise error.Abort(
1329 _(b'%r cannot be used in the name of a patch')
1329 _(b'%r cannot be used in the name of a patch')
1330 % pycompat.bytestr(c)
1330 % pycompat.bytestr(c)
1331 )
1331 )
1332
1332
1333 def checkpatchname(self, name, force=False):
1333 def checkpatchname(self, name, force=False):
1334 self.checkreservedname(name)
1334 self.checkreservedname(name)
1335 if not force and os.path.exists(self.join(name)):
1335 if not force and os.path.exists(self.join(name)):
1336 if os.path.isdir(self.join(name)):
1336 if os.path.isdir(self.join(name)):
1337 raise error.Abort(
1337 raise error.Abort(
1338 _(b'"%s" already exists as a directory') % name
1338 _(b'"%s" already exists as a directory') % name
1339 )
1339 )
1340 else:
1340 else:
1341 raise error.Abort(_(b'patch "%s" already exists') % name)
1341 raise error.Abort(_(b'patch "%s" already exists') % name)
1342
1342
1343 def makepatchname(self, title, fallbackname):
1343 def makepatchname(self, title, fallbackname):
1344 """Return a suitable filename for title, adding a suffix to make
1344 """Return a suitable filename for title, adding a suffix to make
1345 it unique in the existing list"""
1345 it unique in the existing list"""
1346 namebase = re.sub(br'[\s\W_]+', b'_', title.lower()).strip(b'_')
1346 namebase = re.sub(br'[\s\W_]+', b'_', title.lower()).strip(b'_')
1347 namebase = namebase[:75] # avoid too long name (issue5117)
1347 namebase = namebase[:75] # avoid too long name (issue5117)
1348 if namebase:
1348 if namebase:
1349 try:
1349 try:
1350 self.checkreservedname(namebase)
1350 self.checkreservedname(namebase)
1351 except error.Abort:
1351 except error.Abort:
1352 namebase = fallbackname
1352 namebase = fallbackname
1353 else:
1353 else:
1354 namebase = fallbackname
1354 namebase = fallbackname
1355 name = namebase
1355 name = namebase
1356 i = 0
1356 i = 0
1357 while True:
1357 while True:
1358 if name not in self.fullseries:
1358 if name not in self.fullseries:
1359 try:
1359 try:
1360 self.checkpatchname(name)
1360 self.checkpatchname(name)
1361 break
1361 break
1362 except error.Abort:
1362 except error.Abort:
1363 pass
1363 pass
1364 i += 1
1364 i += 1
1365 name = b'%s__%d' % (namebase, i)
1365 name = b'%s__%d' % (namebase, i)
1366 return name
1366 return name
1367
1367
1368 def checkkeepchanges(self, keepchanges, force):
1368 def checkkeepchanges(self, keepchanges, force):
1369 if force and keepchanges:
1369 if force and keepchanges:
1370 raise error.Abort(_(b'cannot use both --force and --keep-changes'))
1370 raise error.Abort(_(b'cannot use both --force and --keep-changes'))
1371
1371
1372 def new(self, repo, patchfn, *pats, **opts):
1372 def new(self, repo, patchfn, *pats, **opts):
1373 """options:
1373 """options:
1374 msg: a string or a no-argument function returning a string
1374 msg: a string or a no-argument function returning a string
1375 """
1375 """
1376 opts = pycompat.byteskwargs(opts)
1376 opts = pycompat.byteskwargs(opts)
1377 msg = opts.get(b'msg')
1377 msg = opts.get(b'msg')
1378 edit = opts.get(b'edit')
1378 edit = opts.get(b'edit')
1379 editform = opts.get(b'editform', b'mq.qnew')
1379 editform = opts.get(b'editform', b'mq.qnew')
1380 user = opts.get(b'user')
1380 user = opts.get(b'user')
1381 date = opts.get(b'date')
1381 date = opts.get(b'date')
1382 if date:
1382 if date:
1383 date = dateutil.parsedate(date)
1383 date = dateutil.parsedate(date)
1384 diffopts = self.diffopts({b'git': opts.get(b'git')}, plain=True)
1384 diffopts = self.diffopts({b'git': opts.get(b'git')}, plain=True)
1385 if opts.get(b'checkname', True):
1385 if opts.get(b'checkname', True):
1386 self.checkpatchname(patchfn)
1386 self.checkpatchname(patchfn)
1387 inclsubs = checksubstate(repo)
1387 inclsubs = checksubstate(repo)
1388 if inclsubs:
1388 if inclsubs:
1389 substatestate = repo.dirstate[b'.hgsubstate']
1389 substatestate = repo.dirstate[b'.hgsubstate']
1390 if opts.get(b'include') or opts.get(b'exclude') or pats:
1390 if opts.get(b'include') or opts.get(b'exclude') or pats:
1391 # detect missing files in pats
1391 # detect missing files in pats
1392 def badfn(f, msg):
1392 def badfn(f, msg):
1393 if f != b'.hgsubstate': # .hgsubstate is auto-created
1393 if f != b'.hgsubstate': # .hgsubstate is auto-created
1394 raise error.Abort(b'%s: %s' % (f, msg))
1394 raise error.Abort(b'%s: %s' % (f, msg))
1395
1395
1396 match = scmutil.match(repo[None], pats, opts, badfn=badfn)
1396 match = scmutil.match(repo[None], pats, opts, badfn=badfn)
1397 changes = repo.status(match=match)
1397 changes = repo.status(match=match)
1398 else:
1398 else:
1399 changes = self.checklocalchanges(repo, force=True)
1399 changes = self.checklocalchanges(repo, force=True)
1400 commitfiles = list(inclsubs)
1400 commitfiles = list(inclsubs)
1401 commitfiles.extend(changes.modified)
1401 commitfiles.extend(changes.modified)
1402 commitfiles.extend(changes.added)
1402 commitfiles.extend(changes.added)
1403 commitfiles.extend(changes.removed)
1403 commitfiles.extend(changes.removed)
1404 match = scmutil.matchfiles(repo, commitfiles)
1404 match = scmutil.matchfiles(repo, commitfiles)
1405 if len(repo[None].parents()) > 1:
1405 if len(repo[None].parents()) > 1:
1406 raise error.Abort(_(b'cannot manage merge changesets'))
1406 raise error.Abort(_(b'cannot manage merge changesets'))
1407 self.checktoppatch(repo)
1407 self.checktoppatch(repo)
1408 insert = self.fullseriesend()
1408 insert = self.fullseriesend()
1409 with repo.wlock():
1409 with repo.wlock():
1410 try:
1410 try:
1411 # if patch file write fails, abort early
1411 # if patch file write fails, abort early
1412 p = self.opener(patchfn, b"w")
1412 p = self.opener(patchfn, b"w")
1413 except IOError as e:
1413 except IOError as e:
1414 raise error.Abort(
1414 raise error.Abort(
1415 _(b'cannot write patch "%s": %s')
1415 _(b'cannot write patch "%s": %s')
1416 % (patchfn, encoding.strtolocal(e.strerror))
1416 % (patchfn, encoding.strtolocal(e.strerror))
1417 )
1417 )
1418 try:
1418 try:
1419 defaultmsg = b"[mq]: %s" % patchfn
1419 defaultmsg = b"[mq]: %s" % patchfn
1420 editor = cmdutil.getcommiteditor(editform=editform)
1420 editor = cmdutil.getcommiteditor(editform=editform)
1421 if edit:
1421 if edit:
1422
1422
1423 def finishdesc(desc):
1423 def finishdesc(desc):
1424 if desc.rstrip():
1424 if desc.rstrip():
1425 return desc
1425 return desc
1426 else:
1426 else:
1427 return defaultmsg
1427 return defaultmsg
1428
1428
1429 # i18n: this message is shown in editor with "HG: " prefix
1429 # i18n: this message is shown in editor with "HG: " prefix
1430 extramsg = _(b'Leave message empty to use default message.')
1430 extramsg = _(b'Leave message empty to use default message.')
1431 editor = cmdutil.getcommiteditor(
1431 editor = cmdutil.getcommiteditor(
1432 finishdesc=finishdesc,
1432 finishdesc=finishdesc,
1433 extramsg=extramsg,
1433 extramsg=extramsg,
1434 editform=editform,
1434 editform=editform,
1435 )
1435 )
1436 commitmsg = msg
1436 commitmsg = msg
1437 else:
1437 else:
1438 commitmsg = msg or defaultmsg
1438 commitmsg = msg or defaultmsg
1439
1439
1440 n = newcommit(
1440 n = newcommit(
1441 repo,
1441 repo,
1442 None,
1442 None,
1443 commitmsg,
1443 commitmsg,
1444 user,
1444 user,
1445 date,
1445 date,
1446 match=match,
1446 match=match,
1447 force=True,
1447 force=True,
1448 editor=editor,
1448 editor=editor,
1449 )
1449 )
1450 if n is None:
1450 if n is None:
1451 raise error.Abort(_(b"repo commit failed"))
1451 raise error.Abort(_(b"repo commit failed"))
1452 try:
1452 try:
1453 self.fullseries[insert:insert] = [patchfn]
1453 self.fullseries[insert:insert] = [patchfn]
1454 self.applied.append(statusentry(n, patchfn))
1454 self.applied.append(statusentry(n, patchfn))
1455 self.parseseries()
1455 self.parseseries()
1456 self.seriesdirty = True
1456 self.seriesdirty = True
1457 self.applieddirty = True
1457 self.applieddirty = True
1458 nctx = repo[n]
1458 nctx = repo[n]
1459 ph = patchheader(self.join(patchfn), self.plainmode)
1459 ph = patchheader(self.join(patchfn), self.plainmode)
1460 if user:
1460 if user:
1461 ph.setuser(user)
1461 ph.setuser(user)
1462 if date:
1462 if date:
1463 ph.setdate(b'%d %d' % date)
1463 ph.setdate(b'%d %d' % date)
1464 ph.setparent(hex(nctx.p1().node()))
1464 ph.setparent(hex(nctx.p1().node()))
1465 msg = nctx.description().strip()
1465 msg = nctx.description().strip()
1466 if msg == defaultmsg.strip():
1466 if msg == defaultmsg.strip():
1467 msg = b''
1467 msg = b''
1468 ph.setmessage(msg)
1468 ph.setmessage(msg)
1469 p.write(bytes(ph))
1469 p.write(bytes(ph))
1470 if commitfiles:
1470 if commitfiles:
1471 parent = self.qparents(repo, n)
1471 parent = self.qparents(repo, n)
1472 if inclsubs:
1472 if inclsubs:
1473 self.putsubstate2changes(substatestate, changes)
1473 self.putsubstate2changes(substatestate, changes)
1474 chunks = patchmod.diff(
1474 chunks = patchmod.diff(
1475 repo,
1475 repo,
1476 node1=parent,
1476 node1=parent,
1477 node2=n,
1477 node2=n,
1478 changes=changes,
1478 changes=changes,
1479 opts=diffopts,
1479 opts=diffopts,
1480 )
1480 )
1481 for chunk in chunks:
1481 for chunk in chunks:
1482 p.write(chunk)
1482 p.write(chunk)
1483 p.close()
1483 p.close()
1484 r = self.qrepo()
1484 r = self.qrepo()
1485 if r:
1485 if r:
1486 r[None].add([patchfn])
1486 r[None].add([patchfn])
1487 except: # re-raises
1487 except: # re-raises
1488 repo.rollback()
1488 repo.rollback()
1489 raise
1489 raise
1490 except Exception:
1490 except Exception:
1491 patchpath = self.join(patchfn)
1491 patchpath = self.join(patchfn)
1492 try:
1492 try:
1493 os.unlink(patchpath)
1493 os.unlink(patchpath)
1494 except OSError:
1494 except OSError:
1495 self.ui.warn(_(b'error unlinking %s\n') % patchpath)
1495 self.ui.warn(_(b'error unlinking %s\n') % patchpath)
1496 raise
1496 raise
1497 self.removeundo(repo)
1497 self.removeundo(repo)
1498
1498
1499 def isapplied(self, patch):
1499 def isapplied(self, patch):
1500 """returns (index, rev, patch)"""
1500 """returns (index, rev, patch)"""
1501 for i, a in enumerate(self.applied):
1501 for i, a in enumerate(self.applied):
1502 if a.name == patch:
1502 if a.name == patch:
1503 return (i, a.node, a.name)
1503 return (i, a.node, a.name)
1504 return None
1504 return None
1505
1505
1506 # if the exact patch name does not exist, we try a few
1506 # if the exact patch name does not exist, we try a few
1507 # variations. If strict is passed, we try only #1
1507 # variations. If strict is passed, we try only #1
1508 #
1508 #
1509 # 1) a number (as string) to indicate an offset in the series file
1509 # 1) a number (as string) to indicate an offset in the series file
1510 # 2) a unique substring of the patch name was given
1510 # 2) a unique substring of the patch name was given
1511 # 3) patchname[-+]num to indicate an offset in the series file
1511 # 3) patchname[-+]num to indicate an offset in the series file
1512 def lookup(self, patch, strict=False):
1512 def lookup(self, patch, strict=False):
1513 def partialname(s):
1513 def partialname(s):
1514 if s in self.series:
1514 if s in self.series:
1515 return s
1515 return s
1516 matches = [x for x in self.series if s in x]
1516 matches = [x for x in self.series if s in x]
1517 if len(matches) > 1:
1517 if len(matches) > 1:
1518 self.ui.warn(_(b'patch name "%s" is ambiguous:\n') % s)
1518 self.ui.warn(_(b'patch name "%s" is ambiguous:\n') % s)
1519 for m in matches:
1519 for m in matches:
1520 self.ui.warn(b' %s\n' % m)
1520 self.ui.warn(b' %s\n' % m)
1521 return None
1521 return None
1522 if matches:
1522 if matches:
1523 return matches[0]
1523 return matches[0]
1524 if self.series and self.applied:
1524 if self.series and self.applied:
1525 if s == b'qtip':
1525 if s == b'qtip':
1526 return self.series[self.seriesend(True) - 1]
1526 return self.series[self.seriesend(True) - 1]
1527 if s == b'qbase':
1527 if s == b'qbase':
1528 return self.series[0]
1528 return self.series[0]
1529 return None
1529 return None
1530
1530
1531 if patch in self.series:
1531 if patch in self.series:
1532 return patch
1532 return patch
1533
1533
1534 if not os.path.isfile(self.join(patch)):
1534 if not os.path.isfile(self.join(patch)):
1535 try:
1535 try:
1536 sno = int(patch)
1536 sno = int(patch)
1537 except (ValueError, OverflowError):
1537 except (ValueError, OverflowError):
1538 pass
1538 pass
1539 else:
1539 else:
1540 if -len(self.series) <= sno < len(self.series):
1540 if -len(self.series) <= sno < len(self.series):
1541 return self.series[sno]
1541 return self.series[sno]
1542
1542
1543 if not strict:
1543 if not strict:
1544 res = partialname(patch)
1544 res = partialname(patch)
1545 if res:
1545 if res:
1546 return res
1546 return res
1547 minus = patch.rfind(b'-')
1547 minus = patch.rfind(b'-')
1548 if minus >= 0:
1548 if minus >= 0:
1549 res = partialname(patch[:minus])
1549 res = partialname(patch[:minus])
1550 if res:
1550 if res:
1551 i = self.series.index(res)
1551 i = self.series.index(res)
1552 try:
1552 try:
1553 off = int(patch[minus + 1 :] or 1)
1553 off = int(patch[minus + 1 :] or 1)
1554 except (ValueError, OverflowError):
1554 except (ValueError, OverflowError):
1555 pass
1555 pass
1556 else:
1556 else:
1557 if i - off >= 0:
1557 if i - off >= 0:
1558 return self.series[i - off]
1558 return self.series[i - off]
1559 plus = patch.rfind(b'+')
1559 plus = patch.rfind(b'+')
1560 if plus >= 0:
1560 if plus >= 0:
1561 res = partialname(patch[:plus])
1561 res = partialname(patch[:plus])
1562 if res:
1562 if res:
1563 i = self.series.index(res)
1563 i = self.series.index(res)
1564 try:
1564 try:
1565 off = int(patch[plus + 1 :] or 1)
1565 off = int(patch[plus + 1 :] or 1)
1566 except (ValueError, OverflowError):
1566 except (ValueError, OverflowError):
1567 pass
1567 pass
1568 else:
1568 else:
1569 if i + off < len(self.series):
1569 if i + off < len(self.series):
1570 return self.series[i + off]
1570 return self.series[i + off]
1571 raise error.Abort(_(b"patch %s not in series") % patch)
1571 raise error.Abort(_(b"patch %s not in series") % patch)
1572
1572
1573 def push(
1573 def push(
1574 self,
1574 self,
1575 repo,
1575 repo,
1576 patch=None,
1576 patch=None,
1577 force=False,
1577 force=False,
1578 list=False,
1578 list=False,
1579 mergeq=None,
1579 mergeq=None,
1580 all=False,
1580 all=False,
1581 move=False,
1581 move=False,
1582 exact=False,
1582 exact=False,
1583 nobackup=False,
1583 nobackup=False,
1584 keepchanges=False,
1584 keepchanges=False,
1585 ):
1585 ):
1586 self.checkkeepchanges(keepchanges, force)
1586 self.checkkeepchanges(keepchanges, force)
1587 diffopts = self.diffopts()
1587 diffopts = self.diffopts()
1588 with repo.wlock():
1588 with repo.wlock():
1589 heads = []
1589 heads = []
1590 for hs in repo.branchmap().iterheads():
1590 for hs in repo.branchmap().iterheads():
1591 heads.extend(hs)
1591 heads.extend(hs)
1592 if not heads:
1592 if not heads:
1593 heads = [repo.nullid]
1593 heads = [repo.nullid]
1594 if repo.dirstate.p1() not in heads and not exact:
1594 if repo.dirstate.p1() not in heads and not exact:
1595 self.ui.status(_(b"(working directory not at a head)\n"))
1595 self.ui.status(_(b"(working directory not at a head)\n"))
1596
1596
1597 if not self.series:
1597 if not self.series:
1598 self.ui.warn(_(b'no patches in series\n'))
1598 self.ui.warn(_(b'no patches in series\n'))
1599 return 0
1599 return 0
1600
1600
1601 # Suppose our series file is: A B C and the current 'top'
1601 # Suppose our series file is: A B C and the current 'top'
1602 # patch is B. qpush C should be performed (moving forward)
1602 # 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
1603 # qpush B is a NOP (no change) qpush A is an error (can't
1604 # go backwards with qpush)
1604 # go backwards with qpush)
1605 if patch:
1605 if patch:
1606 patch = self.lookup(patch)
1606 patch = self.lookup(patch)
1607 info = self.isapplied(patch)
1607 info = self.isapplied(patch)
1608 if info and info[0] >= len(self.applied) - 1:
1608 if info and info[0] >= len(self.applied) - 1:
1609 self.ui.warn(
1609 self.ui.warn(
1610 _(b'qpush: %s is already at the top\n') % patch
1610 _(b'qpush: %s is already at the top\n') % patch
1611 )
1611 )
1612 return 0
1612 return 0
1613
1613
1614 pushable, reason = self.pushable(patch)
1614 pushable, reason = self.pushable(patch)
1615 if pushable:
1615 if pushable:
1616 if self.series.index(patch) < self.seriesend():
1616 if self.series.index(patch) < self.seriesend():
1617 raise error.Abort(
1617 raise error.Abort(
1618 _(b"cannot push to a previous patch: %s") % patch
1618 _(b"cannot push to a previous patch: %s") % patch
1619 )
1619 )
1620 else:
1620 else:
1621 if reason:
1621 if reason:
1622 reason = _(b'guarded by %s') % reason
1622 reason = _(b'guarded by %s') % reason
1623 else:
1623 else:
1624 reason = _(b'no matching guards')
1624 reason = _(b'no matching guards')
1625 self.ui.warn(
1625 self.ui.warn(
1626 _(b"cannot push '%s' - %s\n") % (patch, reason)
1626 _(b"cannot push '%s' - %s\n") % (patch, reason)
1627 )
1627 )
1628 return 1
1628 return 1
1629 elif all:
1629 elif all:
1630 patch = self.series[-1]
1630 patch = self.series[-1]
1631 if self.isapplied(patch):
1631 if self.isapplied(patch):
1632 self.ui.warn(_(b'all patches are currently applied\n'))
1632 self.ui.warn(_(b'all patches are currently applied\n'))
1633 return 0
1633 return 0
1634
1634
1635 # Following the above example, starting at 'top' of B:
1635 # Following the above example, starting at 'top' of B:
1636 # qpush should be performed (pushes C), but a subsequent
1636 # qpush should be performed (pushes C), but a subsequent
1637 # qpush without an argument is an error (nothing to
1637 # qpush without an argument is an error (nothing to
1638 # apply). This allows a loop of "...while hg qpush..." to
1638 # apply). This allows a loop of "...while hg qpush..." to
1639 # work as it detects an error when done
1639 # work as it detects an error when done
1640 start = self.seriesend()
1640 start = self.seriesend()
1641 if start == len(self.series):
1641 if start == len(self.series):
1642 self.ui.warn(_(b'patch series already fully applied\n'))
1642 self.ui.warn(_(b'patch series already fully applied\n'))
1643 return 1
1643 return 1
1644 if not force and not keepchanges:
1644 if not force and not keepchanges:
1645 self.checklocalchanges(repo, refresh=self.applied)
1645 self.checklocalchanges(repo, refresh=self.applied)
1646
1646
1647 if exact:
1647 if exact:
1648 if keepchanges:
1648 if keepchanges:
1649 raise error.Abort(
1649 raise error.Abort(
1650 _(b"cannot use --exact and --keep-changes together")
1650 _(b"cannot use --exact and --keep-changes together")
1651 )
1651 )
1652 if move:
1652 if move:
1653 raise error.Abort(
1653 raise error.Abort(
1654 _(b'cannot use --exact and --move together')
1654 _(b'cannot use --exact and --move together')
1655 )
1655 )
1656 if self.applied:
1656 if self.applied:
1657 raise error.Abort(
1657 raise error.Abort(
1658 _(b'cannot push --exact with applied patches')
1658 _(b'cannot push --exact with applied patches')
1659 )
1659 )
1660 root = self.series[start]
1660 root = self.series[start]
1661 target = patchheader(self.join(root), self.plainmode).parent
1661 target = patchheader(self.join(root), self.plainmode).parent
1662 if not target:
1662 if not target:
1663 raise error.Abort(
1663 raise error.Abort(
1664 _(b"%s does not have a parent recorded") % root
1664 _(b"%s does not have a parent recorded") % root
1665 )
1665 )
1666 if not repo[target] == repo[b'.']:
1666 if not repo[target] == repo[b'.']:
1667 hg.update(repo, target)
1667 hg.update(repo, target)
1668
1668
1669 if move:
1669 if move:
1670 if not patch:
1670 if not patch:
1671 raise error.Abort(_(b"please specify the patch to move"))
1671 raise error.Abort(_(b"please specify the patch to move"))
1672 for fullstart, rpn in enumerate(self.fullseries):
1672 for fullstart, rpn in enumerate(self.fullseries):
1673 # strip markers for patch guards
1673 # strip markers for patch guards
1674 if self.guard_re.split(rpn, 1)[0] == self.series[start]:
1674 if self.guard_re.split(rpn, 1)[0] == self.series[start]:
1675 break
1675 break
1676 for i, rpn in enumerate(self.fullseries[fullstart:]):
1676 for i, rpn in enumerate(self.fullseries[fullstart:]):
1677 # strip markers for patch guards
1677 # strip markers for patch guards
1678 if self.guard_re.split(rpn, 1)[0] == patch:
1678 if self.guard_re.split(rpn, 1)[0] == patch:
1679 break
1679 break
1680 index = fullstart + i
1680 index = fullstart + i
1681 assert index < len(self.fullseries)
1681 assert index < len(self.fullseries)
1682 fullpatch = self.fullseries[index]
1682 fullpatch = self.fullseries[index]
1683 del self.fullseries[index]
1683 del self.fullseries[index]
1684 self.fullseries.insert(fullstart, fullpatch)
1684 self.fullseries.insert(fullstart, fullpatch)
1685 self.parseseries()
1685 self.parseseries()
1686 self.seriesdirty = True
1686 self.seriesdirty = True
1687
1687
1688 self.applieddirty = True
1688 self.applieddirty = True
1689 if start > 0:
1689 if start > 0:
1690 self.checktoppatch(repo)
1690 self.checktoppatch(repo)
1691 if not patch:
1691 if not patch:
1692 patch = self.series[start]
1692 patch = self.series[start]
1693 end = start + 1
1693 end = start + 1
1694 else:
1694 else:
1695 end = self.series.index(patch, start) + 1
1695 end = self.series.index(patch, start) + 1
1696
1696
1697 tobackup = set()
1697 tobackup = set()
1698 if (not nobackup and force) or keepchanges:
1698 if (not nobackup and force) or keepchanges:
1699 status = self.checklocalchanges(repo, force=True)
1699 status = self.checklocalchanges(repo, force=True)
1700 if keepchanges:
1700 if keepchanges:
1701 tobackup.update(
1701 tobackup.update(
1702 status.modified
1702 status.modified
1703 + status.added
1703 + status.added
1704 + status.removed
1704 + status.removed
1705 + status.deleted
1705 + status.deleted
1706 )
1706 )
1707 else:
1707 else:
1708 tobackup.update(status.modified + status.added)
1708 tobackup.update(status.modified + status.added)
1709
1709
1710 s = self.series[start:end]
1710 s = self.series[start:end]
1711 all_files = set()
1711 all_files = set()
1712 try:
1712 try:
1713 if mergeq:
1713 if mergeq:
1714 ret = self.mergepatch(repo, mergeq, s, diffopts)
1714 ret = self.mergepatch(repo, mergeq, s, diffopts)
1715 else:
1715 else:
1716 ret = self.apply(
1716 ret = self.apply(
1717 repo,
1717 repo,
1718 s,
1718 s,
1719 list,
1719 list,
1720 all_files=all_files,
1720 all_files=all_files,
1721 tobackup=tobackup,
1721 tobackup=tobackup,
1722 keepchanges=keepchanges,
1722 keepchanges=keepchanges,
1723 )
1723 )
1724 except AbortNoCleanup:
1724 except AbortNoCleanup:
1725 raise
1725 raise
1726 except: # re-raises
1726 except: # re-raises
1727 self.ui.warn(_(b'cleaning up working directory...\n'))
1727 self.ui.warn(_(b'cleaning up working directory...\n'))
1728 cmdutil.revert(
1728 cmdutil.revert(
1729 self.ui,
1729 self.ui,
1730 repo,
1730 repo,
1731 repo[b'.'],
1731 repo[b'.'],
1732 no_backup=True,
1732 no_backup=True,
1733 )
1733 )
1734 # only remove unknown files that we know we touched or
1734 # only remove unknown files that we know we touched or
1735 # created while patching
1735 # created while patching
1736 for f in all_files:
1736 for f in all_files:
1737 if f not in repo.dirstate:
1737 if f not in repo.dirstate:
1738 repo.wvfs.unlinkpath(f, ignoremissing=True)
1738 repo.wvfs.unlinkpath(f, ignoremissing=True)
1739 self.ui.warn(_(b'done\n'))
1739 self.ui.warn(_(b'done\n'))
1740 raise
1740 raise
1741
1741
1742 if not self.applied:
1742 if not self.applied:
1743 return ret[0]
1743 return ret[0]
1744 top = self.applied[-1].name
1744 top = self.applied[-1].name
1745 if ret[0] and ret[0] > 1:
1745 if ret[0] and ret[0] > 1:
1746 msg = _(b"errors during apply, please fix and qrefresh %s\n")
1746 msg = _(b"errors during apply, please fix and qrefresh %s\n")
1747 self.ui.write(msg % top)
1747 self.ui.write(msg % top)
1748 else:
1748 else:
1749 self.ui.write(_(b"now at: %s\n") % top)
1749 self.ui.write(_(b"now at: %s\n") % top)
1750 return ret[0]
1750 return ret[0]
1751
1751
1752 def pop(
1752 def pop(
1753 self,
1753 self,
1754 repo,
1754 repo,
1755 patch=None,
1755 patch=None,
1756 force=False,
1756 force=False,
1757 update=True,
1757 update=True,
1758 all=False,
1758 all=False,
1759 nobackup=False,
1759 nobackup=False,
1760 keepchanges=False,
1760 keepchanges=False,
1761 ):
1761 ):
1762 self.checkkeepchanges(keepchanges, force)
1762 self.checkkeepchanges(keepchanges, force)
1763 with repo.wlock():
1763 with repo.wlock():
1764 if patch:
1764 if patch:
1765 # index, rev, patch
1765 # index, rev, patch
1766 info = self.isapplied(patch)
1766 info = self.isapplied(patch)
1767 if not info:
1767 if not info:
1768 patch = self.lookup(patch)
1768 patch = self.lookup(patch)
1769 info = self.isapplied(patch)
1769 info = self.isapplied(patch)
1770 if not info:
1770 if not info:
1771 raise error.Abort(_(b"patch %s is not applied") % patch)
1771 raise error.Abort(_(b"patch %s is not applied") % patch)
1772
1772
1773 if not self.applied:
1773 if not self.applied:
1774 # Allow qpop -a to work repeatedly,
1774 # Allow qpop -a to work repeatedly,
1775 # but not qpop without an argument
1775 # but not qpop without an argument
1776 self.ui.warn(_(b"no patches applied\n"))
1776 self.ui.warn(_(b"no patches applied\n"))
1777 return not all
1777 return not all
1778
1778
1779 if all:
1779 if all:
1780 start = 0
1780 start = 0
1781 elif patch:
1781 elif patch:
1782 start = info[0] + 1
1782 start = info[0] + 1
1783 else:
1783 else:
1784 start = len(self.applied) - 1
1784 start = len(self.applied) - 1
1785
1785
1786 if start >= len(self.applied):
1786 if start >= len(self.applied):
1787 self.ui.warn(_(b"qpop: %s is already at the top\n") % patch)
1787 self.ui.warn(_(b"qpop: %s is already at the top\n") % patch)
1788 return
1788 return
1789
1789
1790 if not update:
1790 if not update:
1791 parents = repo.dirstate.parents()
1791 parents = repo.dirstate.parents()
1792 rr = [x.node for x in self.applied]
1792 rr = [x.node for x in self.applied]
1793 for p in parents:
1793 for p in parents:
1794 if p in rr:
1794 if p in rr:
1795 self.ui.warn(_(b"qpop: forcing dirstate update\n"))
1795 self.ui.warn(_(b"qpop: forcing dirstate update\n"))
1796 update = True
1796 update = True
1797 else:
1797 else:
1798 parents = [p.node() for p in repo[None].parents()]
1798 parents = [p.node() for p in repo[None].parents()]
1799 update = any(
1799 update = any(
1800 entry.node in parents for entry in self.applied[start:]
1800 entry.node in parents for entry in self.applied[start:]
1801 )
1801 )
1802
1802
1803 tobackup = set()
1803 tobackup = set()
1804 if update:
1804 if update:
1805 s = self.checklocalchanges(repo, force=force or keepchanges)
1805 s = self.checklocalchanges(repo, force=force or keepchanges)
1806 if force:
1806 if force:
1807 if not nobackup:
1807 if not nobackup:
1808 tobackup.update(s.modified + s.added)
1808 tobackup.update(s.modified + s.added)
1809 elif keepchanges:
1809 elif keepchanges:
1810 tobackup.update(
1810 tobackup.update(
1811 s.modified + s.added + s.removed + s.deleted
1811 s.modified + s.added + s.removed + s.deleted
1812 )
1812 )
1813
1813
1814 self.applieddirty = True
1814 self.applieddirty = True
1815 end = len(self.applied)
1815 end = len(self.applied)
1816 rev = self.applied[start].node
1816 rev = self.applied[start].node
1817
1817
1818 try:
1818 try:
1819 heads = repo.changelog.heads(rev)
1819 heads = repo.changelog.heads(rev)
1820 except error.LookupError:
1820 except error.LookupError:
1821 node = short(rev)
1821 node = short(rev)
1822 raise error.Abort(_(b'trying to pop unknown node %s') % node)
1822 raise error.Abort(_(b'trying to pop unknown node %s') % node)
1823
1823
1824 if heads != [self.applied[-1].node]:
1824 if heads != [self.applied[-1].node]:
1825 raise error.Abort(
1825 raise error.Abort(
1826 _(
1826 _(
1827 b"popping would remove a revision not "
1827 b"popping would remove a revision not "
1828 b"managed by this patch queue"
1828 b"managed by this patch queue"
1829 )
1829 )
1830 )
1830 )
1831 if not repo[self.applied[-1].node].mutable():
1831 if not repo[self.applied[-1].node].mutable():
1832 raise error.Abort(
1832 raise error.Abort(
1833 _(b"popping would remove a public revision"),
1833 _(b"popping would remove a public revision"),
1834 hint=_(b"see 'hg help phases' for details"),
1834 hint=_(b"see 'hg help phases' for details"),
1835 )
1835 )
1836
1836
1837 # we know there are no local changes, so we can make a simplified
1837 # we know there are no local changes, so we can make a simplified
1838 # form of hg.update.
1838 # form of hg.update.
1839 if update:
1839 if update:
1840 qp = self.qparents(repo, rev)
1840 qp = self.qparents(repo, rev)
1841 ctx = repo[qp]
1841 ctx = repo[qp]
1842 st = repo.status(qp, b'.')
1842 st = repo.status(qp, b'.')
1843 m, a, r, d = st.modified, st.added, st.removed, st.deleted
1843 m, a, r, d = st.modified, st.added, st.removed, st.deleted
1844 if d:
1844 if d:
1845 raise error.Abort(_(b"deletions found between repo revs"))
1845 raise error.Abort(_(b"deletions found between repo revs"))
1846
1846
1847 tobackup = set(a + m + r) & tobackup
1847 tobackup = set(a + m + r) & tobackup
1848 if keepchanges and tobackup:
1848 if keepchanges and tobackup:
1849 raise error.Abort(_(b"local changes found, qrefresh first"))
1849 raise error.Abort(_(b"local changes found, qrefresh first"))
1850 self.backup(repo, tobackup)
1850 self.backup(repo, tobackup)
1851 with repo.dirstate.parentchange():
1851 with repo.dirstate.parentchange():
1852 for f in a:
1852 for f in a:
1853 repo.wvfs.unlinkpath(f, ignoremissing=True)
1853 repo.wvfs.unlinkpath(f, ignoremissing=True)
1854 repo.dirstate.drop(f)
1854 repo.dirstate.drop(f)
1855 for f in m + r:
1855 for f in m + r:
1856 fctx = ctx[f]
1856 fctx = ctx[f]
1857 repo.wwrite(f, fctx.data(), fctx.flags())
1857 repo.wwrite(f, fctx.data(), fctx.flags())
1858 repo.dirstate.normal(f)
1858 repo.dirstate.update_file(
1859 f, p1_tracked=True, wc_tracked=True
1860 )
1859 repo.setparents(qp, repo.nullid)
1861 repo.setparents(qp, repo.nullid)
1860 for patch in reversed(self.applied[start:end]):
1862 for patch in reversed(self.applied[start:end]):
1861 self.ui.status(_(b"popping %s\n") % patch.name)
1863 self.ui.status(_(b"popping %s\n") % patch.name)
1862 del self.applied[start:end]
1864 del self.applied[start:end]
1863 strip(self.ui, repo, [rev], update=False, backup=False)
1865 strip(self.ui, repo, [rev], update=False, backup=False)
1864 for s, state in repo[b'.'].substate.items():
1866 for s, state in repo[b'.'].substate.items():
1865 repo[b'.'].sub(s).get(state)
1867 repo[b'.'].sub(s).get(state)
1866 if self.applied:
1868 if self.applied:
1867 self.ui.write(_(b"now at: %s\n") % self.applied[-1].name)
1869 self.ui.write(_(b"now at: %s\n") % self.applied[-1].name)
1868 else:
1870 else:
1869 self.ui.write(_(b"patch queue now empty\n"))
1871 self.ui.write(_(b"patch queue now empty\n"))
1870
1872
1871 def diff(self, repo, pats, opts):
1873 def diff(self, repo, pats, opts):
1872 top, patch = self.checktoppatch(repo)
1874 top, patch = self.checktoppatch(repo)
1873 if not top:
1875 if not top:
1874 self.ui.write(_(b"no patches applied\n"))
1876 self.ui.write(_(b"no patches applied\n"))
1875 return
1877 return
1876 qp = self.qparents(repo, top)
1878 qp = self.qparents(repo, top)
1877 if opts.get(b'reverse'):
1879 if opts.get(b'reverse'):
1878 node1, node2 = None, qp
1880 node1, node2 = None, qp
1879 else:
1881 else:
1880 node1, node2 = qp, None
1882 node1, node2 = qp, None
1881 diffopts = self.diffopts(opts, patch)
1883 diffopts = self.diffopts(opts, patch)
1882 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1884 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1883
1885
1884 def refresh(self, repo, pats=None, **opts):
1886 def refresh(self, repo, pats=None, **opts):
1885 opts = pycompat.byteskwargs(opts)
1887 opts = pycompat.byteskwargs(opts)
1886 if not self.applied:
1888 if not self.applied:
1887 self.ui.write(_(b"no patches applied\n"))
1889 self.ui.write(_(b"no patches applied\n"))
1888 return 1
1890 return 1
1889 msg = opts.get(b'msg', b'').rstrip()
1891 msg = opts.get(b'msg', b'').rstrip()
1890 edit = opts.get(b'edit')
1892 edit = opts.get(b'edit')
1891 editform = opts.get(b'editform', b'mq.qrefresh')
1893 editform = opts.get(b'editform', b'mq.qrefresh')
1892 newuser = opts.get(b'user')
1894 newuser = opts.get(b'user')
1893 newdate = opts.get(b'date')
1895 newdate = opts.get(b'date')
1894 if newdate:
1896 if newdate:
1895 newdate = b'%d %d' % dateutil.parsedate(newdate)
1897 newdate = b'%d %d' % dateutil.parsedate(newdate)
1896 wlock = repo.wlock()
1898 wlock = repo.wlock()
1897
1899
1898 try:
1900 try:
1899 self.checktoppatch(repo)
1901 self.checktoppatch(repo)
1900 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1902 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1901 if repo.changelog.heads(top) != [top]:
1903 if repo.changelog.heads(top) != [top]:
1902 raise error.Abort(
1904 raise error.Abort(
1903 _(b"cannot qrefresh a revision with children")
1905 _(b"cannot qrefresh a revision with children")
1904 )
1906 )
1905 if not repo[top].mutable():
1907 if not repo[top].mutable():
1906 raise error.Abort(
1908 raise error.Abort(
1907 _(b"cannot qrefresh public revision"),
1909 _(b"cannot qrefresh public revision"),
1908 hint=_(b"see 'hg help phases' for details"),
1910 hint=_(b"see 'hg help phases' for details"),
1909 )
1911 )
1910
1912
1911 cparents = repo.changelog.parents(top)
1913 cparents = repo.changelog.parents(top)
1912 patchparent = self.qparents(repo, top)
1914 patchparent = self.qparents(repo, top)
1913
1915
1914 inclsubs = checksubstate(repo, patchparent)
1916 inclsubs = checksubstate(repo, patchparent)
1915 if inclsubs:
1917 if inclsubs:
1916 substatestate = repo.dirstate[b'.hgsubstate']
1918 substatestate = repo.dirstate[b'.hgsubstate']
1917
1919
1918 ph = patchheader(self.join(patchfn), self.plainmode)
1920 ph = patchheader(self.join(patchfn), self.plainmode)
1919 diffopts = self.diffopts(
1921 diffopts = self.diffopts(
1920 {b'git': opts.get(b'git')}, patchfn, plain=True
1922 {b'git': opts.get(b'git')}, patchfn, plain=True
1921 )
1923 )
1922 if newuser:
1924 if newuser:
1923 ph.setuser(newuser)
1925 ph.setuser(newuser)
1924 if newdate:
1926 if newdate:
1925 ph.setdate(newdate)
1927 ph.setdate(newdate)
1926 ph.setparent(hex(patchparent))
1928 ph.setparent(hex(patchparent))
1927
1929
1928 # only commit new patch when write is complete
1930 # only commit new patch when write is complete
1929 patchf = self.opener(patchfn, b'w', atomictemp=True)
1931 patchf = self.opener(patchfn, b'w', atomictemp=True)
1930
1932
1931 # update the dirstate in place, strip off the qtip commit
1933 # update the dirstate in place, strip off the qtip commit
1932 # and then commit.
1934 # and then commit.
1933 #
1935 #
1934 # this should really read:
1936 # this should really read:
1935 # st = repo.status(top, patchparent)
1937 # st = repo.status(top, patchparent)
1936 # but we do it backwards to take advantage of manifest/changelog
1938 # but we do it backwards to take advantage of manifest/changelog
1937 # caching against the next repo.status call
1939 # caching against the next repo.status call
1938 st = repo.status(patchparent, top)
1940 st = repo.status(patchparent, top)
1939 mm, aa, dd = st.modified, st.added, st.removed
1941 mm, aa, dd = st.modified, st.added, st.removed
1940 ctx = repo[top]
1942 ctx = repo[top]
1941 aaa = aa[:]
1943 aaa = aa[:]
1942 match1 = scmutil.match(repo[None], pats, opts)
1944 match1 = scmutil.match(repo[None], pats, opts)
1943 # in short mode, we only diff the files included in the
1945 # in short mode, we only diff the files included in the
1944 # patch already plus specified files
1946 # patch already plus specified files
1945 if opts.get(b'short'):
1947 if opts.get(b'short'):
1946 # if amending a patch, we start with existing
1948 # if amending a patch, we start with existing
1947 # files plus specified files - unfiltered
1949 # files plus specified files - unfiltered
1948 match = scmutil.matchfiles(repo, mm + aa + dd + match1.files())
1950 match = scmutil.matchfiles(repo, mm + aa + dd + match1.files())
1949 # filter with include/exclude options
1951 # filter with include/exclude options
1950 match1 = scmutil.match(repo[None], opts=opts)
1952 match1 = scmutil.match(repo[None], opts=opts)
1951 else:
1953 else:
1952 match = scmutil.matchall(repo)
1954 match = scmutil.matchall(repo)
1953 stb = repo.status(match=match)
1955 stb = repo.status(match=match)
1954 m, a, r, d = stb.modified, stb.added, stb.removed, stb.deleted
1956 m, a, r, d = stb.modified, stb.added, stb.removed, stb.deleted
1955 mm = set(mm)
1957 mm = set(mm)
1956 aa = set(aa)
1958 aa = set(aa)
1957 dd = set(dd)
1959 dd = set(dd)
1958
1960
1959 # we might end up with files that were added between
1961 # we might end up with files that were added between
1960 # qtip and the dirstate parent, but then changed in the
1962 # qtip and the dirstate parent, but then changed in the
1961 # local dirstate. in this case, we want them to only
1963 # local dirstate. in this case, we want them to only
1962 # show up in the added section
1964 # show up in the added section
1963 for x in m:
1965 for x in m:
1964 if x not in aa:
1966 if x not in aa:
1965 mm.add(x)
1967 mm.add(x)
1966 # we might end up with files added by the local dirstate that
1968 # we might end up with files added by the local dirstate that
1967 # were deleted by the patch. In this case, they should only
1969 # were deleted by the patch. In this case, they should only
1968 # show up in the changed section.
1970 # show up in the changed section.
1969 for x in a:
1971 for x in a:
1970 if x in dd:
1972 if x in dd:
1971 dd.remove(x)
1973 dd.remove(x)
1972 mm.add(x)
1974 mm.add(x)
1973 else:
1975 else:
1974 aa.add(x)
1976 aa.add(x)
1975 # make sure any files deleted in the local dirstate
1977 # make sure any files deleted in the local dirstate
1976 # are not in the add or change column of the patch
1978 # are not in the add or change column of the patch
1977 forget = []
1979 forget = []
1978 for x in d + r:
1980 for x in d + r:
1979 if x in aa:
1981 if x in aa:
1980 aa.remove(x)
1982 aa.remove(x)
1981 forget.append(x)
1983 forget.append(x)
1982 continue
1984 continue
1983 else:
1985 else:
1984 mm.discard(x)
1986 mm.discard(x)
1985 dd.add(x)
1987 dd.add(x)
1986
1988
1987 m = list(mm)
1989 m = list(mm)
1988 r = list(dd)
1990 r = list(dd)
1989 a = list(aa)
1991 a = list(aa)
1990
1992
1991 # create 'match' that includes the files to be recommitted.
1993 # create 'match' that includes the files to be recommitted.
1992 # apply match1 via repo.status to ensure correct case handling.
1994 # apply match1 via repo.status to ensure correct case handling.
1993 st = repo.status(patchparent, match=match1)
1995 st = repo.status(patchparent, match=match1)
1994 cm, ca, cr, cd = st.modified, st.added, st.removed, st.deleted
1996 cm, ca, cr, cd = st.modified, st.added, st.removed, st.deleted
1995 allmatches = set(cm + ca + cr + cd)
1997 allmatches = set(cm + ca + cr + cd)
1996 refreshchanges = [x.intersection(allmatches) for x in (mm, aa, dd)]
1998 refreshchanges = [x.intersection(allmatches) for x in (mm, aa, dd)]
1997
1999
1998 files = set(inclsubs)
2000 files = set(inclsubs)
1999 for x in refreshchanges:
2001 for x in refreshchanges:
2000 files.update(x)
2002 files.update(x)
2001 match = scmutil.matchfiles(repo, files)
2003 match = scmutil.matchfiles(repo, files)
2002
2004
2003 bmlist = repo[top].bookmarks()
2005 bmlist = repo[top].bookmarks()
2004
2006
2005 with repo.dirstate.parentchange():
2007 with repo.dirstate.parentchange():
2006 # XXX do we actually need the dirstateguard
2008 # XXX do we actually need the dirstateguard
2007 dsguard = None
2009 dsguard = None
2008 try:
2010 try:
2009 dsguard = dirstateguard.dirstateguard(repo, b'mq.refresh')
2011 dsguard = dirstateguard.dirstateguard(repo, b'mq.refresh')
2010 if diffopts.git or diffopts.upgrade:
2012 if diffopts.git or diffopts.upgrade:
2011 copies = {}
2013 copies = {}
2012 for dst in a:
2014 for dst in a:
2013 src = repo.dirstate.copied(dst)
2015 src = repo.dirstate.copied(dst)
2014 # during qfold, the source file for copies may
2016 # during qfold, the source file for copies may
2015 # be removed. Treat this as a simple add.
2017 # be removed. Treat this as a simple add.
2016 if src is not None and src in repo.dirstate:
2018 if src is not None and src in repo.dirstate:
2017 copies.setdefault(src, []).append(dst)
2019 copies.setdefault(src, []).append(dst)
2018 repo.dirstate.add(dst)
2020 repo.dirstate.add(dst)
2019 # remember the copies between patchparent and qtip
2021 # remember the copies between patchparent and qtip
2020 for dst in aaa:
2022 for dst in aaa:
2021 src = ctx[dst].copysource()
2023 src = ctx[dst].copysource()
2022 if src:
2024 if src:
2023 copies.setdefault(src, []).extend(
2025 copies.setdefault(src, []).extend(
2024 copies.get(dst, [])
2026 copies.get(dst, [])
2025 )
2027 )
2026 if dst in a:
2028 if dst in a:
2027 copies[src].append(dst)
2029 copies[src].append(dst)
2028 # we can't copy a file created by the patch itself
2030 # we can't copy a file created by the patch itself
2029 if dst in copies:
2031 if dst in copies:
2030 del copies[dst]
2032 del copies[dst]
2031 for src, dsts in pycompat.iteritems(copies):
2033 for src, dsts in pycompat.iteritems(copies):
2032 for dst in dsts:
2034 for dst in dsts:
2033 repo.dirstate.copy(src, dst)
2035 repo.dirstate.copy(src, dst)
2034 else:
2036 else:
2035 for dst in a:
2037 for dst in a:
2036 repo.dirstate.add(dst)
2038 repo.dirstate.add(dst)
2037 # Drop useless copy information
2039 # Drop useless copy information
2038 for f in list(repo.dirstate.copies()):
2040 for f in list(repo.dirstate.copies()):
2039 repo.dirstate.copy(None, f)
2041 repo.dirstate.copy(None, f)
2040 for f in r:
2042 for f in r:
2041 repo.dirstate.update_file_p1(f, p1_tracked=True)
2043 repo.dirstate.update_file_p1(f, p1_tracked=True)
2042 # if the patch excludes a modified file, mark that
2044 # if the patch excludes a modified file, mark that
2043 # file with mtime=0 so status can see it.
2045 # file with mtime=0 so status can see it.
2044 mm = []
2046 mm = []
2045 for i in pycompat.xrange(len(m) - 1, -1, -1):
2047 for i in pycompat.xrange(len(m) - 1, -1, -1):
2046 if not match1(m[i]):
2048 if not match1(m[i]):
2047 mm.append(m[i])
2049 mm.append(m[i])
2048 del m[i]
2050 del m[i]
2049 for f in m:
2051 for f in m:
2050 repo.dirstate.normal(f)
2052 repo.dirstate.update_file_p1(f, p1_tracked=True)
2051 for f in mm:
2053 for f in mm:
2052 repo.dirstate.normallookup(f)
2054 repo.dirstate.normallookup(f)
2053 for f in forget:
2055 for f in forget:
2054 repo.dirstate.drop(f)
2056 repo.dirstate.drop(f)
2055
2057
2056 user = ph.user or ctx.user()
2058 user = ph.user or ctx.user()
2057
2059
2058 oldphase = repo[top].phase()
2060 oldphase = repo[top].phase()
2059
2061
2060 # assumes strip can roll itself back if interrupted
2062 # assumes strip can roll itself back if interrupted
2061 repo.setparents(*cparents)
2063 repo.setparents(*cparents)
2062 self.applied.pop()
2064 self.applied.pop()
2063 self.applieddirty = True
2065 self.applieddirty = True
2064 strip(self.ui, repo, [top], update=False, backup=False)
2066 strip(self.ui, repo, [top], update=False, backup=False)
2065 dsguard.close()
2067 dsguard.close()
2066 finally:
2068 finally:
2067 release(dsguard)
2069 release(dsguard)
2068
2070
2069 try:
2071 try:
2070 # might be nice to attempt to roll back strip after this
2072 # might be nice to attempt to roll back strip after this
2071
2073
2072 defaultmsg = b"[mq]: %s" % patchfn
2074 defaultmsg = b"[mq]: %s" % patchfn
2073 editor = cmdutil.getcommiteditor(editform=editform)
2075 editor = cmdutil.getcommiteditor(editform=editform)
2074 if edit:
2076 if edit:
2075
2077
2076 def finishdesc(desc):
2078 def finishdesc(desc):
2077 if desc.rstrip():
2079 if desc.rstrip():
2078 ph.setmessage(desc)
2080 ph.setmessage(desc)
2079 return desc
2081 return desc
2080 return defaultmsg
2082 return defaultmsg
2081
2083
2082 # i18n: this message is shown in editor with "HG: " prefix
2084 # i18n: this message is shown in editor with "HG: " prefix
2083 extramsg = _(b'Leave message empty to use default message.')
2085 extramsg = _(b'Leave message empty to use default message.')
2084 editor = cmdutil.getcommiteditor(
2086 editor = cmdutil.getcommiteditor(
2085 finishdesc=finishdesc,
2087 finishdesc=finishdesc,
2086 extramsg=extramsg,
2088 extramsg=extramsg,
2087 editform=editform,
2089 editform=editform,
2088 )
2090 )
2089 message = msg or b"\n".join(ph.message)
2091 message = msg or b"\n".join(ph.message)
2090 elif not msg:
2092 elif not msg:
2091 if not ph.message:
2093 if not ph.message:
2092 message = defaultmsg
2094 message = defaultmsg
2093 else:
2095 else:
2094 message = b"\n".join(ph.message)
2096 message = b"\n".join(ph.message)
2095 else:
2097 else:
2096 message = msg
2098 message = msg
2097 ph.setmessage(msg)
2099 ph.setmessage(msg)
2098
2100
2099 # Ensure we create a new changeset in the same phase than
2101 # Ensure we create a new changeset in the same phase than
2100 # the old one.
2102 # the old one.
2101 lock = tr = None
2103 lock = tr = None
2102 try:
2104 try:
2103 lock = repo.lock()
2105 lock = repo.lock()
2104 tr = repo.transaction(b'mq')
2106 tr = repo.transaction(b'mq')
2105 n = newcommit(
2107 n = newcommit(
2106 repo,
2108 repo,
2107 oldphase,
2109 oldphase,
2108 message,
2110 message,
2109 user,
2111 user,
2110 ph.date,
2112 ph.date,
2111 match=match,
2113 match=match,
2112 force=True,
2114 force=True,
2113 editor=editor,
2115 editor=editor,
2114 )
2116 )
2115 # only write patch after a successful commit
2117 # only write patch after a successful commit
2116 c = [list(x) for x in refreshchanges]
2118 c = [list(x) for x in refreshchanges]
2117 if inclsubs:
2119 if inclsubs:
2118 self.putsubstate2changes(substatestate, c)
2120 self.putsubstate2changes(substatestate, c)
2119 chunks = patchmod.diff(
2121 chunks = patchmod.diff(
2120 repo, patchparent, changes=c, opts=diffopts
2122 repo, patchparent, changes=c, opts=diffopts
2121 )
2123 )
2122 comments = bytes(ph)
2124 comments = bytes(ph)
2123 if comments:
2125 if comments:
2124 patchf.write(comments)
2126 patchf.write(comments)
2125 for chunk in chunks:
2127 for chunk in chunks:
2126 patchf.write(chunk)
2128 patchf.write(chunk)
2127 patchf.close()
2129 patchf.close()
2128
2130
2129 marks = repo._bookmarks
2131 marks = repo._bookmarks
2130 marks.applychanges(repo, tr, [(bm, n) for bm in bmlist])
2132 marks.applychanges(repo, tr, [(bm, n) for bm in bmlist])
2131 tr.close()
2133 tr.close()
2132
2134
2133 self.applied.append(statusentry(n, patchfn))
2135 self.applied.append(statusentry(n, patchfn))
2134 finally:
2136 finally:
2135 lockmod.release(tr, lock)
2137 lockmod.release(tr, lock)
2136 except: # re-raises
2138 except: # re-raises
2137 ctx = repo[cparents[0]]
2139 ctx = repo[cparents[0]]
2138 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2140 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2139 self.savedirty()
2141 self.savedirty()
2140 self.ui.warn(
2142 self.ui.warn(
2141 _(
2143 _(
2142 b'qrefresh interrupted while patch was popped! '
2144 b'qrefresh interrupted while patch was popped! '
2143 b'(revert --all, qpush to recover)\n'
2145 b'(revert --all, qpush to recover)\n'
2144 )
2146 )
2145 )
2147 )
2146 raise
2148 raise
2147 finally:
2149 finally:
2148 wlock.release()
2150 wlock.release()
2149 self.removeundo(repo)
2151 self.removeundo(repo)
2150
2152
2151 def init(self, repo, create=False):
2153 def init(self, repo, create=False):
2152 if not create and os.path.isdir(self.path):
2154 if not create and os.path.isdir(self.path):
2153 raise error.Abort(_(b"patch queue directory already exists"))
2155 raise error.Abort(_(b"patch queue directory already exists"))
2154 try:
2156 try:
2155 os.mkdir(self.path)
2157 os.mkdir(self.path)
2156 except OSError as inst:
2158 except OSError as inst:
2157 if inst.errno != errno.EEXIST or not create:
2159 if inst.errno != errno.EEXIST or not create:
2158 raise
2160 raise
2159 if create:
2161 if create:
2160 return self.qrepo(create=True)
2162 return self.qrepo(create=True)
2161
2163
2162 def unapplied(self, repo, patch=None):
2164 def unapplied(self, repo, patch=None):
2163 if patch and patch not in self.series:
2165 if patch and patch not in self.series:
2164 raise error.Abort(_(b"patch %s is not in series file") % patch)
2166 raise error.Abort(_(b"patch %s is not in series file") % patch)
2165 if not patch:
2167 if not patch:
2166 start = self.seriesend()
2168 start = self.seriesend()
2167 else:
2169 else:
2168 start = self.series.index(patch) + 1
2170 start = self.series.index(patch) + 1
2169 unapplied = []
2171 unapplied = []
2170 for i in pycompat.xrange(start, len(self.series)):
2172 for i in pycompat.xrange(start, len(self.series)):
2171 pushable, reason = self.pushable(i)
2173 pushable, reason = self.pushable(i)
2172 if pushable:
2174 if pushable:
2173 unapplied.append((i, self.series[i]))
2175 unapplied.append((i, self.series[i]))
2174 self.explainpushable(i)
2176 self.explainpushable(i)
2175 return unapplied
2177 return unapplied
2176
2178
2177 def qseries(
2179 def qseries(
2178 self,
2180 self,
2179 repo,
2181 repo,
2180 missing=None,
2182 missing=None,
2181 start=0,
2183 start=0,
2182 length=None,
2184 length=None,
2183 status=None,
2185 status=None,
2184 summary=False,
2186 summary=False,
2185 ):
2187 ):
2186 def displayname(pfx, patchname, state):
2188 def displayname(pfx, patchname, state):
2187 if pfx:
2189 if pfx:
2188 self.ui.write(pfx)
2190 self.ui.write(pfx)
2189 if summary:
2191 if summary:
2190 ph = patchheader(self.join(patchname), self.plainmode)
2192 ph = patchheader(self.join(patchname), self.plainmode)
2191 if ph.message:
2193 if ph.message:
2192 msg = ph.message[0]
2194 msg = ph.message[0]
2193 else:
2195 else:
2194 msg = b''
2196 msg = b''
2195
2197
2196 if self.ui.formatted():
2198 if self.ui.formatted():
2197 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
2199 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
2198 if width > 0:
2200 if width > 0:
2199 msg = stringutil.ellipsis(msg, width)
2201 msg = stringutil.ellipsis(msg, width)
2200 else:
2202 else:
2201 msg = b''
2203 msg = b''
2202 self.ui.write(patchname, label=b'qseries.' + state)
2204 self.ui.write(patchname, label=b'qseries.' + state)
2203 self.ui.write(b': ')
2205 self.ui.write(b': ')
2204 self.ui.write(msg, label=b'qseries.message.' + state)
2206 self.ui.write(msg, label=b'qseries.message.' + state)
2205 else:
2207 else:
2206 self.ui.write(patchname, label=b'qseries.' + state)
2208 self.ui.write(patchname, label=b'qseries.' + state)
2207 self.ui.write(b'\n')
2209 self.ui.write(b'\n')
2208
2210
2209 applied = {p.name for p in self.applied}
2211 applied = {p.name for p in self.applied}
2210 if length is None:
2212 if length is None:
2211 length = len(self.series) - start
2213 length = len(self.series) - start
2212 if not missing:
2214 if not missing:
2213 if self.ui.verbose:
2215 if self.ui.verbose:
2214 idxwidth = len(b"%d" % (start + length - 1))
2216 idxwidth = len(b"%d" % (start + length - 1))
2215 for i in pycompat.xrange(start, start + length):
2217 for i in pycompat.xrange(start, start + length):
2216 patch = self.series[i]
2218 patch = self.series[i]
2217 if patch in applied:
2219 if patch in applied:
2218 char, state = b'A', b'applied'
2220 char, state = b'A', b'applied'
2219 elif self.pushable(i)[0]:
2221 elif self.pushable(i)[0]:
2220 char, state = b'U', b'unapplied'
2222 char, state = b'U', b'unapplied'
2221 else:
2223 else:
2222 char, state = b'G', b'guarded'
2224 char, state = b'G', b'guarded'
2223 pfx = b''
2225 pfx = b''
2224 if self.ui.verbose:
2226 if self.ui.verbose:
2225 pfx = b'%*d %s ' % (idxwidth, i, char)
2227 pfx = b'%*d %s ' % (idxwidth, i, char)
2226 elif status and status != char:
2228 elif status and status != char:
2227 continue
2229 continue
2228 displayname(pfx, patch, state)
2230 displayname(pfx, patch, state)
2229 else:
2231 else:
2230 msng_list = []
2232 msng_list = []
2231 for root, dirs, files in os.walk(self.path):
2233 for root, dirs, files in os.walk(self.path):
2232 d = root[len(self.path) + 1 :]
2234 d = root[len(self.path) + 1 :]
2233 for f in files:
2235 for f in files:
2234 fl = os.path.join(d, f)
2236 fl = os.path.join(d, f)
2235 if (
2237 if (
2236 fl not in self.series
2238 fl not in self.series
2237 and fl
2239 and fl
2238 not in (
2240 not in (
2239 self.statuspath,
2241 self.statuspath,
2240 self.seriespath,
2242 self.seriespath,
2241 self.guardspath,
2243 self.guardspath,
2242 )
2244 )
2243 and not fl.startswith(b'.')
2245 and not fl.startswith(b'.')
2244 ):
2246 ):
2245 msng_list.append(fl)
2247 msng_list.append(fl)
2246 for x in sorted(msng_list):
2248 for x in sorted(msng_list):
2247 pfx = self.ui.verbose and b'D ' or b''
2249 pfx = self.ui.verbose and b'D ' or b''
2248 displayname(pfx, x, b'missing')
2250 displayname(pfx, x, b'missing')
2249
2251
2250 def issaveline(self, l):
2252 def issaveline(self, l):
2251 if l.name == b'.hg.patches.save.line':
2253 if l.name == b'.hg.patches.save.line':
2252 return True
2254 return True
2253
2255
2254 def qrepo(self, create=False):
2256 def qrepo(self, create=False):
2255 ui = self.baseui.copy()
2257 ui = self.baseui.copy()
2256 # copy back attributes set by ui.pager()
2258 # copy back attributes set by ui.pager()
2257 if self.ui.pageractive and not ui.pageractive:
2259 if self.ui.pageractive and not ui.pageractive:
2258 ui.pageractive = self.ui.pageractive
2260 ui.pageractive = self.ui.pageractive
2259 # internal config: ui.formatted
2261 # internal config: ui.formatted
2260 ui.setconfig(
2262 ui.setconfig(
2261 b'ui',
2263 b'ui',
2262 b'formatted',
2264 b'formatted',
2263 self.ui.config(b'ui', b'formatted'),
2265 self.ui.config(b'ui', b'formatted'),
2264 b'mqpager',
2266 b'mqpager',
2265 )
2267 )
2266 ui.setconfig(
2268 ui.setconfig(
2267 b'ui',
2269 b'ui',
2268 b'interactive',
2270 b'interactive',
2269 self.ui.config(b'ui', b'interactive'),
2271 self.ui.config(b'ui', b'interactive'),
2270 b'mqpager',
2272 b'mqpager',
2271 )
2273 )
2272 if create or os.path.isdir(self.join(b".hg")):
2274 if create or os.path.isdir(self.join(b".hg")):
2273 return hg.repository(ui, path=self.path, create=create)
2275 return hg.repository(ui, path=self.path, create=create)
2274
2276
2275 def restore(self, repo, rev, delete=None, qupdate=None):
2277 def restore(self, repo, rev, delete=None, qupdate=None):
2276 desc = repo[rev].description().strip()
2278 desc = repo[rev].description().strip()
2277 lines = desc.splitlines()
2279 lines = desc.splitlines()
2278 datastart = None
2280 datastart = None
2279 series = []
2281 series = []
2280 applied = []
2282 applied = []
2281 qpp = None
2283 qpp = None
2282 for i, line in enumerate(lines):
2284 for i, line in enumerate(lines):
2283 if line == b'Patch Data:':
2285 if line == b'Patch Data:':
2284 datastart = i + 1
2286 datastart = i + 1
2285 elif line.startswith(b'Dirstate:'):
2287 elif line.startswith(b'Dirstate:'):
2286 l = line.rstrip()
2288 l = line.rstrip()
2287 l = l[10:].split(b' ')
2289 l = l[10:].split(b' ')
2288 qpp = [bin(x) for x in l]
2290 qpp = [bin(x) for x in l]
2289 elif datastart is not None:
2291 elif datastart is not None:
2290 l = line.rstrip()
2292 l = line.rstrip()
2291 n, name = l.split(b':', 1)
2293 n, name = l.split(b':', 1)
2292 if n:
2294 if n:
2293 applied.append(statusentry(bin(n), name))
2295 applied.append(statusentry(bin(n), name))
2294 else:
2296 else:
2295 series.append(l)
2297 series.append(l)
2296 if datastart is None:
2298 if datastart is None:
2297 self.ui.warn(_(b"no saved patch data found\n"))
2299 self.ui.warn(_(b"no saved patch data found\n"))
2298 return 1
2300 return 1
2299 self.ui.warn(_(b"restoring status: %s\n") % lines[0])
2301 self.ui.warn(_(b"restoring status: %s\n") % lines[0])
2300 self.fullseries = series
2302 self.fullseries = series
2301 self.applied = applied
2303 self.applied = applied
2302 self.parseseries()
2304 self.parseseries()
2303 self.seriesdirty = True
2305 self.seriesdirty = True
2304 self.applieddirty = True
2306 self.applieddirty = True
2305 heads = repo.changelog.heads()
2307 heads = repo.changelog.heads()
2306 if delete:
2308 if delete:
2307 if rev not in heads:
2309 if rev not in heads:
2308 self.ui.warn(_(b"save entry has children, leaving it alone\n"))
2310 self.ui.warn(_(b"save entry has children, leaving it alone\n"))
2309 else:
2311 else:
2310 self.ui.warn(_(b"removing save entry %s\n") % short(rev))
2312 self.ui.warn(_(b"removing save entry %s\n") % short(rev))
2311 pp = repo.dirstate.parents()
2313 pp = repo.dirstate.parents()
2312 if rev in pp:
2314 if rev in pp:
2313 update = True
2315 update = True
2314 else:
2316 else:
2315 update = False
2317 update = False
2316 strip(self.ui, repo, [rev], update=update, backup=False)
2318 strip(self.ui, repo, [rev], update=update, backup=False)
2317 if qpp:
2319 if qpp:
2318 self.ui.warn(
2320 self.ui.warn(
2319 _(b"saved queue repository parents: %s %s\n")
2321 _(b"saved queue repository parents: %s %s\n")
2320 % (short(qpp[0]), short(qpp[1]))
2322 % (short(qpp[0]), short(qpp[1]))
2321 )
2323 )
2322 if qupdate:
2324 if qupdate:
2323 self.ui.status(_(b"updating queue directory\n"))
2325 self.ui.status(_(b"updating queue directory\n"))
2324 r = self.qrepo()
2326 r = self.qrepo()
2325 if not r:
2327 if not r:
2326 self.ui.warn(_(b"unable to load queue repository\n"))
2328 self.ui.warn(_(b"unable to load queue repository\n"))
2327 return 1
2329 return 1
2328 hg.clean(r, qpp[0])
2330 hg.clean(r, qpp[0])
2329
2331
2330 def save(self, repo, msg=None):
2332 def save(self, repo, msg=None):
2331 if not self.applied:
2333 if not self.applied:
2332 self.ui.warn(_(b"save: no patches applied, exiting\n"))
2334 self.ui.warn(_(b"save: no patches applied, exiting\n"))
2333 return 1
2335 return 1
2334 if self.issaveline(self.applied[-1]):
2336 if self.issaveline(self.applied[-1]):
2335 self.ui.warn(_(b"status is already saved\n"))
2337 self.ui.warn(_(b"status is already saved\n"))
2336 return 1
2338 return 1
2337
2339
2338 if not msg:
2340 if not msg:
2339 msg = _(b"hg patches saved state")
2341 msg = _(b"hg patches saved state")
2340 else:
2342 else:
2341 msg = b"hg patches: " + msg.rstrip(b'\r\n')
2343 msg = b"hg patches: " + msg.rstrip(b'\r\n')
2342 r = self.qrepo()
2344 r = self.qrepo()
2343 if r:
2345 if r:
2344 pp = r.dirstate.parents()
2346 pp = r.dirstate.parents()
2345 msg += b"\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
2347 msg += b"\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
2346 msg += b"\n\nPatch Data:\n"
2348 msg += b"\n\nPatch Data:\n"
2347 msg += b''.join(b'%s\n' % x for x in self.applied)
2349 msg += b''.join(b'%s\n' % x for x in self.applied)
2348 msg += b''.join(b':%s\n' % x for x in self.fullseries)
2350 msg += b''.join(b':%s\n' % x for x in self.fullseries)
2349 n = repo.commit(msg, force=True)
2351 n = repo.commit(msg, force=True)
2350 if not n:
2352 if not n:
2351 self.ui.warn(_(b"repo commit failed\n"))
2353 self.ui.warn(_(b"repo commit failed\n"))
2352 return 1
2354 return 1
2353 self.applied.append(statusentry(n, b'.hg.patches.save.line'))
2355 self.applied.append(statusentry(n, b'.hg.patches.save.line'))
2354 self.applieddirty = True
2356 self.applieddirty = True
2355 self.removeundo(repo)
2357 self.removeundo(repo)
2356
2358
2357 def fullseriesend(self):
2359 def fullseriesend(self):
2358 if self.applied:
2360 if self.applied:
2359 p = self.applied[-1].name
2361 p = self.applied[-1].name
2360 end = self.findseries(p)
2362 end = self.findseries(p)
2361 if end is None:
2363 if end is None:
2362 return len(self.fullseries)
2364 return len(self.fullseries)
2363 return end + 1
2365 return end + 1
2364 return 0
2366 return 0
2365
2367
2366 def seriesend(self, all_patches=False):
2368 def seriesend(self, all_patches=False):
2367 """If all_patches is False, return the index of the next pushable patch
2369 """If all_patches is False, return the index of the next pushable patch
2368 in the series, or the series length. If all_patches is True, return the
2370 in the series, or the series length. If all_patches is True, return the
2369 index of the first patch past the last applied one.
2371 index of the first patch past the last applied one.
2370 """
2372 """
2371 end = 0
2373 end = 0
2372
2374
2373 def nextpatch(start):
2375 def nextpatch(start):
2374 if all_patches or start >= len(self.series):
2376 if all_patches or start >= len(self.series):
2375 return start
2377 return start
2376 for i in pycompat.xrange(start, len(self.series)):
2378 for i in pycompat.xrange(start, len(self.series)):
2377 p, reason = self.pushable(i)
2379 p, reason = self.pushable(i)
2378 if p:
2380 if p:
2379 return i
2381 return i
2380 self.explainpushable(i)
2382 self.explainpushable(i)
2381 return len(self.series)
2383 return len(self.series)
2382
2384
2383 if self.applied:
2385 if self.applied:
2384 p = self.applied[-1].name
2386 p = self.applied[-1].name
2385 try:
2387 try:
2386 end = self.series.index(p)
2388 end = self.series.index(p)
2387 except ValueError:
2389 except ValueError:
2388 return 0
2390 return 0
2389 return nextpatch(end + 1)
2391 return nextpatch(end + 1)
2390 return nextpatch(end)
2392 return nextpatch(end)
2391
2393
2392 def appliedname(self, index):
2394 def appliedname(self, index):
2393 pname = self.applied[index].name
2395 pname = self.applied[index].name
2394 if not self.ui.verbose:
2396 if not self.ui.verbose:
2395 p = pname
2397 p = pname
2396 else:
2398 else:
2397 p = (b"%d" % self.series.index(pname)) + b" " + pname
2399 p = (b"%d" % self.series.index(pname)) + b" " + pname
2398 return p
2400 return p
2399
2401
2400 def qimport(
2402 def qimport(
2401 self,
2403 self,
2402 repo,
2404 repo,
2403 files,
2405 files,
2404 patchname=None,
2406 patchname=None,
2405 rev=None,
2407 rev=None,
2406 existing=None,
2408 existing=None,
2407 force=None,
2409 force=None,
2408 git=False,
2410 git=False,
2409 ):
2411 ):
2410 def checkseries(patchname):
2412 def checkseries(patchname):
2411 if patchname in self.series:
2413 if patchname in self.series:
2412 raise error.Abort(
2414 raise error.Abort(
2413 _(b'patch %s is already in the series file') % patchname
2415 _(b'patch %s is already in the series file') % patchname
2414 )
2416 )
2415
2417
2416 if rev:
2418 if rev:
2417 if files:
2419 if files:
2418 raise error.Abort(
2420 raise error.Abort(
2419 _(b'option "-r" not valid when importing files')
2421 _(b'option "-r" not valid when importing files')
2420 )
2422 )
2421 rev = scmutil.revrange(repo, rev)
2423 rev = scmutil.revrange(repo, rev)
2422 rev.sort(reverse=True)
2424 rev.sort(reverse=True)
2423 elif not files:
2425 elif not files:
2424 raise error.Abort(_(b'no files or revisions specified'))
2426 raise error.Abort(_(b'no files or revisions specified'))
2425 if (len(files) > 1 or len(rev) > 1) and patchname:
2427 if (len(files) > 1 or len(rev) > 1) and patchname:
2426 raise error.Abort(
2428 raise error.Abort(
2427 _(b'option "-n" not valid when importing multiple patches')
2429 _(b'option "-n" not valid when importing multiple patches')
2428 )
2430 )
2429 imported = []
2431 imported = []
2430 if rev:
2432 if rev:
2431 # If mq patches are applied, we can only import revisions
2433 # If mq patches are applied, we can only import revisions
2432 # that form a linear path to qbase.
2434 # that form a linear path to qbase.
2433 # Otherwise, they should form a linear path to a head.
2435 # Otherwise, they should form a linear path to a head.
2434 heads = repo.changelog.heads(repo.changelog.node(rev.first()))
2436 heads = repo.changelog.heads(repo.changelog.node(rev.first()))
2435 if len(heads) > 1:
2437 if len(heads) > 1:
2436 raise error.Abort(
2438 raise error.Abort(
2437 _(b'revision %d is the root of more than one branch')
2439 _(b'revision %d is the root of more than one branch')
2438 % rev.last()
2440 % rev.last()
2439 )
2441 )
2440 if self.applied:
2442 if self.applied:
2441 base = repo.changelog.node(rev.first())
2443 base = repo.changelog.node(rev.first())
2442 if base in [n.node for n in self.applied]:
2444 if base in [n.node for n in self.applied]:
2443 raise error.Abort(
2445 raise error.Abort(
2444 _(b'revision %d is already managed') % rev.first()
2446 _(b'revision %d is already managed') % rev.first()
2445 )
2447 )
2446 if heads != [self.applied[-1].node]:
2448 if heads != [self.applied[-1].node]:
2447 raise error.Abort(
2449 raise error.Abort(
2448 _(b'revision %d is not the parent of the queue')
2450 _(b'revision %d is not the parent of the queue')
2449 % rev.first()
2451 % rev.first()
2450 )
2452 )
2451 base = repo.changelog.rev(self.applied[0].node)
2453 base = repo.changelog.rev(self.applied[0].node)
2452 lastparent = repo.changelog.parentrevs(base)[0]
2454 lastparent = repo.changelog.parentrevs(base)[0]
2453 else:
2455 else:
2454 if heads != [repo.changelog.node(rev.first())]:
2456 if heads != [repo.changelog.node(rev.first())]:
2455 raise error.Abort(
2457 raise error.Abort(
2456 _(b'revision %d has unmanaged children') % rev.first()
2458 _(b'revision %d has unmanaged children') % rev.first()
2457 )
2459 )
2458 lastparent = None
2460 lastparent = None
2459
2461
2460 diffopts = self.diffopts({b'git': git})
2462 diffopts = self.diffopts({b'git': git})
2461 with repo.transaction(b'qimport') as tr:
2463 with repo.transaction(b'qimport') as tr:
2462 for r in rev:
2464 for r in rev:
2463 if not repo[r].mutable():
2465 if not repo[r].mutable():
2464 raise error.Abort(
2466 raise error.Abort(
2465 _(b'revision %d is not mutable') % r,
2467 _(b'revision %d is not mutable') % r,
2466 hint=_(b"see 'hg help phases' " b'for details'),
2468 hint=_(b"see 'hg help phases' " b'for details'),
2467 )
2469 )
2468 p1, p2 = repo.changelog.parentrevs(r)
2470 p1, p2 = repo.changelog.parentrevs(r)
2469 n = repo.changelog.node(r)
2471 n = repo.changelog.node(r)
2470 if p2 != nullrev:
2472 if p2 != nullrev:
2471 raise error.Abort(
2473 raise error.Abort(
2472 _(b'cannot import merge revision %d') % r
2474 _(b'cannot import merge revision %d') % r
2473 )
2475 )
2474 if lastparent and lastparent != r:
2476 if lastparent and lastparent != r:
2475 raise error.Abort(
2477 raise error.Abort(
2476 _(b'revision %d is not the parent of %d')
2478 _(b'revision %d is not the parent of %d')
2477 % (r, lastparent)
2479 % (r, lastparent)
2478 )
2480 )
2479 lastparent = p1
2481 lastparent = p1
2480
2482
2481 if not patchname:
2483 if not patchname:
2482 patchname = self.makepatchname(
2484 patchname = self.makepatchname(
2483 repo[r].description().split(b'\n', 1)[0],
2485 repo[r].description().split(b'\n', 1)[0],
2484 b'%d.diff' % r,
2486 b'%d.diff' % r,
2485 )
2487 )
2486 checkseries(patchname)
2488 checkseries(patchname)
2487 self.checkpatchname(patchname, force)
2489 self.checkpatchname(patchname, force)
2488 self.fullseries.insert(0, patchname)
2490 self.fullseries.insert(0, patchname)
2489
2491
2490 with self.opener(patchname, b"w") as fp:
2492 with self.opener(patchname, b"w") as fp:
2491 cmdutil.exportfile(repo, [n], fp, opts=diffopts)
2493 cmdutil.exportfile(repo, [n], fp, opts=diffopts)
2492
2494
2493 se = statusentry(n, patchname)
2495 se = statusentry(n, patchname)
2494 self.applied.insert(0, se)
2496 self.applied.insert(0, se)
2495
2497
2496 self.added.append(patchname)
2498 self.added.append(patchname)
2497 imported.append(patchname)
2499 imported.append(patchname)
2498 patchname = None
2500 patchname = None
2499 if rev and repo.ui.configbool(b'mq', b'secret'):
2501 if rev and repo.ui.configbool(b'mq', b'secret'):
2500 # if we added anything with --rev, move the secret root
2502 # if we added anything with --rev, move the secret root
2501 phases.retractboundary(repo, tr, phases.secret, [n])
2503 phases.retractboundary(repo, tr, phases.secret, [n])
2502 self.parseseries()
2504 self.parseseries()
2503 self.applieddirty = True
2505 self.applieddirty = True
2504 self.seriesdirty = True
2506 self.seriesdirty = True
2505
2507
2506 for i, filename in enumerate(files):
2508 for i, filename in enumerate(files):
2507 if existing:
2509 if existing:
2508 if filename == b'-':
2510 if filename == b'-':
2509 raise error.Abort(
2511 raise error.Abort(
2510 _(b'-e is incompatible with import from -')
2512 _(b'-e is incompatible with import from -')
2511 )
2513 )
2512 filename = normname(filename)
2514 filename = normname(filename)
2513 self.checkreservedname(filename)
2515 self.checkreservedname(filename)
2514 if urlutil.url(filename).islocal():
2516 if urlutil.url(filename).islocal():
2515 originpath = self.join(filename)
2517 originpath = self.join(filename)
2516 if not os.path.isfile(originpath):
2518 if not os.path.isfile(originpath):
2517 raise error.Abort(
2519 raise error.Abort(
2518 _(b"patch %s does not exist") % filename
2520 _(b"patch %s does not exist") % filename
2519 )
2521 )
2520
2522
2521 if patchname:
2523 if patchname:
2522 self.checkpatchname(patchname, force)
2524 self.checkpatchname(patchname, force)
2523
2525
2524 self.ui.write(
2526 self.ui.write(
2525 _(b'renaming %s to %s\n') % (filename, patchname)
2527 _(b'renaming %s to %s\n') % (filename, patchname)
2526 )
2528 )
2527 util.rename(originpath, self.join(patchname))
2529 util.rename(originpath, self.join(patchname))
2528 else:
2530 else:
2529 patchname = filename
2531 patchname = filename
2530
2532
2531 else:
2533 else:
2532 if filename == b'-' and not patchname:
2534 if filename == b'-' and not patchname:
2533 raise error.Abort(
2535 raise error.Abort(
2534 _(b'need --name to import a patch from -')
2536 _(b'need --name to import a patch from -')
2535 )
2537 )
2536 elif not patchname:
2538 elif not patchname:
2537 patchname = normname(
2539 patchname = normname(
2538 os.path.basename(filename.rstrip(b'/'))
2540 os.path.basename(filename.rstrip(b'/'))
2539 )
2541 )
2540 self.checkpatchname(patchname, force)
2542 self.checkpatchname(patchname, force)
2541 try:
2543 try:
2542 if filename == b'-':
2544 if filename == b'-':
2543 text = self.ui.fin.read()
2545 text = self.ui.fin.read()
2544 else:
2546 else:
2545 fp = hg.openpath(self.ui, filename)
2547 fp = hg.openpath(self.ui, filename)
2546 text = fp.read()
2548 text = fp.read()
2547 fp.close()
2549 fp.close()
2548 except (OSError, IOError):
2550 except (OSError, IOError):
2549 raise error.Abort(_(b"unable to read file %s") % filename)
2551 raise error.Abort(_(b"unable to read file %s") % filename)
2550 patchf = self.opener(patchname, b"w")
2552 patchf = self.opener(patchname, b"w")
2551 patchf.write(text)
2553 patchf.write(text)
2552 patchf.close()
2554 patchf.close()
2553 if not force:
2555 if not force:
2554 checkseries(patchname)
2556 checkseries(patchname)
2555 if patchname not in self.series:
2557 if patchname not in self.series:
2556 index = self.fullseriesend() + i
2558 index = self.fullseriesend() + i
2557 self.fullseries[index:index] = [patchname]
2559 self.fullseries[index:index] = [patchname]
2558 self.parseseries()
2560 self.parseseries()
2559 self.seriesdirty = True
2561 self.seriesdirty = True
2560 self.ui.warn(_(b"adding %s to series file\n") % patchname)
2562 self.ui.warn(_(b"adding %s to series file\n") % patchname)
2561 self.added.append(patchname)
2563 self.added.append(patchname)
2562 imported.append(patchname)
2564 imported.append(patchname)
2563 patchname = None
2565 patchname = None
2564
2566
2565 self.removeundo(repo)
2567 self.removeundo(repo)
2566 return imported
2568 return imported
2567
2569
2568
2570
2569 def fixkeepchangesopts(ui, opts):
2571 def fixkeepchangesopts(ui, opts):
2570 if (
2572 if (
2571 not ui.configbool(b'mq', b'keepchanges')
2573 not ui.configbool(b'mq', b'keepchanges')
2572 or opts.get(b'force')
2574 or opts.get(b'force')
2573 or opts.get(b'exact')
2575 or opts.get(b'exact')
2574 ):
2576 ):
2575 return opts
2577 return opts
2576 opts = dict(opts)
2578 opts = dict(opts)
2577 opts[b'keep_changes'] = True
2579 opts[b'keep_changes'] = True
2578 return opts
2580 return opts
2579
2581
2580
2582
2581 @command(
2583 @command(
2582 b"qdelete|qremove|qrm",
2584 b"qdelete|qremove|qrm",
2583 [
2585 [
2584 (b'k', b'keep', None, _(b'keep patch file')),
2586 (b'k', b'keep', None, _(b'keep patch file')),
2585 (
2587 (
2586 b'r',
2588 b'r',
2587 b'rev',
2589 b'rev',
2588 [],
2590 [],
2589 _(b'stop managing a revision (DEPRECATED)'),
2591 _(b'stop managing a revision (DEPRECATED)'),
2590 _(b'REV'),
2592 _(b'REV'),
2591 ),
2593 ),
2592 ],
2594 ],
2593 _(b'hg qdelete [-k] [PATCH]...'),
2595 _(b'hg qdelete [-k] [PATCH]...'),
2594 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2596 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2595 )
2597 )
2596 def delete(ui, repo, *patches, **opts):
2598 def delete(ui, repo, *patches, **opts):
2597 """remove patches from queue
2599 """remove patches from queue
2598
2600
2599 The patches must not be applied, and at least one patch is required. Exact
2601 The patches must not be applied, and at least one patch is required. Exact
2600 patch identifiers must be given. With -k/--keep, the patch files are
2602 patch identifiers must be given. With -k/--keep, the patch files are
2601 preserved in the patch directory.
2603 preserved in the patch directory.
2602
2604
2603 To stop managing a patch and move it into permanent history,
2605 To stop managing a patch and move it into permanent history,
2604 use the :hg:`qfinish` command."""
2606 use the :hg:`qfinish` command."""
2605 q = repo.mq
2607 q = repo.mq
2606 q.delete(repo, patches, pycompat.byteskwargs(opts))
2608 q.delete(repo, patches, pycompat.byteskwargs(opts))
2607 q.savedirty()
2609 q.savedirty()
2608 return 0
2610 return 0
2609
2611
2610
2612
2611 @command(
2613 @command(
2612 b"qapplied",
2614 b"qapplied",
2613 [(b'1', b'last', None, _(b'show only the preceding applied patch'))]
2615 [(b'1', b'last', None, _(b'show only the preceding applied patch'))]
2614 + seriesopts,
2616 + seriesopts,
2615 _(b'hg qapplied [-1] [-s] [PATCH]'),
2617 _(b'hg qapplied [-1] [-s] [PATCH]'),
2616 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2618 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2617 )
2619 )
2618 def applied(ui, repo, patch=None, **opts):
2620 def applied(ui, repo, patch=None, **opts):
2619 """print the patches already applied
2621 """print the patches already applied
2620
2622
2621 Returns 0 on success."""
2623 Returns 0 on success."""
2622
2624
2623 q = repo.mq
2625 q = repo.mq
2624 opts = pycompat.byteskwargs(opts)
2626 opts = pycompat.byteskwargs(opts)
2625
2627
2626 if patch:
2628 if patch:
2627 if patch not in q.series:
2629 if patch not in q.series:
2628 raise error.Abort(_(b"patch %s is not in series file") % patch)
2630 raise error.Abort(_(b"patch %s is not in series file") % patch)
2629 end = q.series.index(patch) + 1
2631 end = q.series.index(patch) + 1
2630 else:
2632 else:
2631 end = q.seriesend(True)
2633 end = q.seriesend(True)
2632
2634
2633 if opts.get(b'last') and not end:
2635 if opts.get(b'last') and not end:
2634 ui.write(_(b"no patches applied\n"))
2636 ui.write(_(b"no patches applied\n"))
2635 return 1
2637 return 1
2636 elif opts.get(b'last') and end == 1:
2638 elif opts.get(b'last') and end == 1:
2637 ui.write(_(b"only one patch applied\n"))
2639 ui.write(_(b"only one patch applied\n"))
2638 return 1
2640 return 1
2639 elif opts.get(b'last'):
2641 elif opts.get(b'last'):
2640 start = end - 2
2642 start = end - 2
2641 end = 1
2643 end = 1
2642 else:
2644 else:
2643 start = 0
2645 start = 0
2644
2646
2645 q.qseries(
2647 q.qseries(
2646 repo, length=end, start=start, status=b'A', summary=opts.get(b'summary')
2648 repo, length=end, start=start, status=b'A', summary=opts.get(b'summary')
2647 )
2649 )
2648
2650
2649
2651
2650 @command(
2652 @command(
2651 b"qunapplied",
2653 b"qunapplied",
2652 [(b'1', b'first', None, _(b'show only the first patch'))] + seriesopts,
2654 [(b'1', b'first', None, _(b'show only the first patch'))] + seriesopts,
2653 _(b'hg qunapplied [-1] [-s] [PATCH]'),
2655 _(b'hg qunapplied [-1] [-s] [PATCH]'),
2654 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2656 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2655 )
2657 )
2656 def unapplied(ui, repo, patch=None, **opts):
2658 def unapplied(ui, repo, patch=None, **opts):
2657 """print the patches not yet applied
2659 """print the patches not yet applied
2658
2660
2659 Returns 0 on success."""
2661 Returns 0 on success."""
2660
2662
2661 q = repo.mq
2663 q = repo.mq
2662 opts = pycompat.byteskwargs(opts)
2664 opts = pycompat.byteskwargs(opts)
2663 if patch:
2665 if patch:
2664 if patch not in q.series:
2666 if patch not in q.series:
2665 raise error.Abort(_(b"patch %s is not in series file") % patch)
2667 raise error.Abort(_(b"patch %s is not in series file") % patch)
2666 start = q.series.index(patch) + 1
2668 start = q.series.index(patch) + 1
2667 else:
2669 else:
2668 start = q.seriesend(True)
2670 start = q.seriesend(True)
2669
2671
2670 if start == len(q.series) and opts.get(b'first'):
2672 if start == len(q.series) and opts.get(b'first'):
2671 ui.write(_(b"all patches applied\n"))
2673 ui.write(_(b"all patches applied\n"))
2672 return 1
2674 return 1
2673
2675
2674 if opts.get(b'first'):
2676 if opts.get(b'first'):
2675 length = 1
2677 length = 1
2676 else:
2678 else:
2677 length = None
2679 length = None
2678 q.qseries(
2680 q.qseries(
2679 repo,
2681 repo,
2680 start=start,
2682 start=start,
2681 length=length,
2683 length=length,
2682 status=b'U',
2684 status=b'U',
2683 summary=opts.get(b'summary'),
2685 summary=opts.get(b'summary'),
2684 )
2686 )
2685
2687
2686
2688
2687 @command(
2689 @command(
2688 b"qimport",
2690 b"qimport",
2689 [
2691 [
2690 (b'e', b'existing', None, _(b'import file in patch directory')),
2692 (b'e', b'existing', None, _(b'import file in patch directory')),
2691 (b'n', b'name', b'', _(b'name of patch file'), _(b'NAME')),
2693 (b'n', b'name', b'', _(b'name of patch file'), _(b'NAME')),
2692 (b'f', b'force', None, _(b'overwrite existing files')),
2694 (b'f', b'force', None, _(b'overwrite existing files')),
2693 (
2695 (
2694 b'r',
2696 b'r',
2695 b'rev',
2697 b'rev',
2696 [],
2698 [],
2697 _(b'place existing revisions under mq control'),
2699 _(b'place existing revisions under mq control'),
2698 _(b'REV'),
2700 _(b'REV'),
2699 ),
2701 ),
2700 (b'g', b'git', None, _(b'use git extended diff format')),
2702 (b'g', b'git', None, _(b'use git extended diff format')),
2701 (b'P', b'push', None, _(b'qpush after importing')),
2703 (b'P', b'push', None, _(b'qpush after importing')),
2702 ],
2704 ],
2703 _(b'hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... [FILE]...'),
2705 _(b'hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... [FILE]...'),
2704 helpcategory=command.CATEGORY_IMPORT_EXPORT,
2706 helpcategory=command.CATEGORY_IMPORT_EXPORT,
2705 )
2707 )
2706 def qimport(ui, repo, *filename, **opts):
2708 def qimport(ui, repo, *filename, **opts):
2707 """import a patch or existing changeset
2709 """import a patch or existing changeset
2708
2710
2709 The patch is inserted into the series after the last applied
2711 The patch is inserted into the series after the last applied
2710 patch. If no patches have been applied, qimport prepends the patch
2712 patch. If no patches have been applied, qimport prepends the patch
2711 to the series.
2713 to the series.
2712
2714
2713 The patch will have the same name as its source file unless you
2715 The patch will have the same name as its source file unless you
2714 give it a new one with -n/--name.
2716 give it a new one with -n/--name.
2715
2717
2716 You can register an existing patch inside the patch directory with
2718 You can register an existing patch inside the patch directory with
2717 the -e/--existing flag.
2719 the -e/--existing flag.
2718
2720
2719 With -f/--force, an existing patch of the same name will be
2721 With -f/--force, an existing patch of the same name will be
2720 overwritten.
2722 overwritten.
2721
2723
2722 An existing changeset may be placed under mq control with -r/--rev
2724 An existing changeset may be placed under mq control with -r/--rev
2723 (e.g. qimport --rev . -n patch will place the current revision
2725 (e.g. qimport --rev . -n patch will place the current revision
2724 under mq control). With -g/--git, patches imported with --rev will
2726 under mq control). With -g/--git, patches imported with --rev will
2725 use the git diff format. See the diffs help topic for information
2727 use the git diff format. See the diffs help topic for information
2726 on why this is important for preserving rename/copy information
2728 on why this is important for preserving rename/copy information
2727 and permission changes. Use :hg:`qfinish` to remove changesets
2729 and permission changes. Use :hg:`qfinish` to remove changesets
2728 from mq control.
2730 from mq control.
2729
2731
2730 To import a patch from standard input, pass - as the patch file.
2732 To import a patch from standard input, pass - as the patch file.
2731 When importing from standard input, a patch name must be specified
2733 When importing from standard input, a patch name must be specified
2732 using the --name flag.
2734 using the --name flag.
2733
2735
2734 To import an existing patch while renaming it::
2736 To import an existing patch while renaming it::
2735
2737
2736 hg qimport -e existing-patch -n new-name
2738 hg qimport -e existing-patch -n new-name
2737
2739
2738 Returns 0 if import succeeded.
2740 Returns 0 if import succeeded.
2739 """
2741 """
2740 opts = pycompat.byteskwargs(opts)
2742 opts = pycompat.byteskwargs(opts)
2741 with repo.lock(): # cause this may move phase
2743 with repo.lock(): # cause this may move phase
2742 q = repo.mq
2744 q = repo.mq
2743 try:
2745 try:
2744 imported = q.qimport(
2746 imported = q.qimport(
2745 repo,
2747 repo,
2746 filename,
2748 filename,
2747 patchname=opts.get(b'name'),
2749 patchname=opts.get(b'name'),
2748 existing=opts.get(b'existing'),
2750 existing=opts.get(b'existing'),
2749 force=opts.get(b'force'),
2751 force=opts.get(b'force'),
2750 rev=opts.get(b'rev'),
2752 rev=opts.get(b'rev'),
2751 git=opts.get(b'git'),
2753 git=opts.get(b'git'),
2752 )
2754 )
2753 finally:
2755 finally:
2754 q.savedirty()
2756 q.savedirty()
2755
2757
2756 if imported and opts.get(b'push') and not opts.get(b'rev'):
2758 if imported and opts.get(b'push') and not opts.get(b'rev'):
2757 return q.push(repo, imported[-1])
2759 return q.push(repo, imported[-1])
2758 return 0
2760 return 0
2759
2761
2760
2762
2761 def qinit(ui, repo, create):
2763 def qinit(ui, repo, create):
2762 """initialize a new queue repository
2764 """initialize a new queue repository
2763
2765
2764 This command also creates a series file for ordering patches, and
2766 This command also creates a series file for ordering patches, and
2765 an mq-specific .hgignore file in the queue repository, to exclude
2767 an mq-specific .hgignore file in the queue repository, to exclude
2766 the status and guards files (these contain mostly transient state).
2768 the status and guards files (these contain mostly transient state).
2767
2769
2768 Returns 0 if initialization succeeded."""
2770 Returns 0 if initialization succeeded."""
2769 q = repo.mq
2771 q = repo.mq
2770 r = q.init(repo, create)
2772 r = q.init(repo, create)
2771 q.savedirty()
2773 q.savedirty()
2772 if r:
2774 if r:
2773 if not os.path.exists(r.wjoin(b'.hgignore')):
2775 if not os.path.exists(r.wjoin(b'.hgignore')):
2774 fp = r.wvfs(b'.hgignore', b'w')
2776 fp = r.wvfs(b'.hgignore', b'w')
2775 fp.write(b'^\\.hg\n')
2777 fp.write(b'^\\.hg\n')
2776 fp.write(b'^\\.mq\n')
2778 fp.write(b'^\\.mq\n')
2777 fp.write(b'syntax: glob\n')
2779 fp.write(b'syntax: glob\n')
2778 fp.write(b'status\n')
2780 fp.write(b'status\n')
2779 fp.write(b'guards\n')
2781 fp.write(b'guards\n')
2780 fp.close()
2782 fp.close()
2781 if not os.path.exists(r.wjoin(b'series')):
2783 if not os.path.exists(r.wjoin(b'series')):
2782 r.wvfs(b'series', b'w').close()
2784 r.wvfs(b'series', b'w').close()
2783 r[None].add([b'.hgignore', b'series'])
2785 r[None].add([b'.hgignore', b'series'])
2784 commands.add(ui, r)
2786 commands.add(ui, r)
2785 return 0
2787 return 0
2786
2788
2787
2789
2788 @command(
2790 @command(
2789 b"qinit",
2791 b"qinit",
2790 [(b'c', b'create-repo', None, _(b'create queue repository'))],
2792 [(b'c', b'create-repo', None, _(b'create queue repository'))],
2791 _(b'hg qinit [-c]'),
2793 _(b'hg qinit [-c]'),
2792 helpcategory=command.CATEGORY_REPO_CREATION,
2794 helpcategory=command.CATEGORY_REPO_CREATION,
2793 helpbasic=True,
2795 helpbasic=True,
2794 )
2796 )
2795 def init(ui, repo, **opts):
2797 def init(ui, repo, **opts):
2796 """init a new queue repository (DEPRECATED)
2798 """init a new queue repository (DEPRECATED)
2797
2799
2798 The queue repository is unversioned by default. If
2800 The queue repository is unversioned by default. If
2799 -c/--create-repo is specified, qinit will create a separate nested
2801 -c/--create-repo is specified, qinit will create a separate nested
2800 repository for patches (qinit -c may also be run later to convert
2802 repository for patches (qinit -c may also be run later to convert
2801 an unversioned patch repository into a versioned one). You can use
2803 an unversioned patch repository into a versioned one). You can use
2802 qcommit to commit changes to this queue repository.
2804 qcommit to commit changes to this queue repository.
2803
2805
2804 This command is deprecated. Without -c, it's implied by other relevant
2806 This command is deprecated. Without -c, it's implied by other relevant
2805 commands. With -c, use :hg:`init --mq` instead."""
2807 commands. With -c, use :hg:`init --mq` instead."""
2806 return qinit(ui, repo, create=opts.get('create_repo'))
2808 return qinit(ui, repo, create=opts.get('create_repo'))
2807
2809
2808
2810
2809 @command(
2811 @command(
2810 b"qclone",
2812 b"qclone",
2811 [
2813 [
2812 (b'', b'pull', None, _(b'use pull protocol to copy metadata')),
2814 (b'', b'pull', None, _(b'use pull protocol to copy metadata')),
2813 (
2815 (
2814 b'U',
2816 b'U',
2815 b'noupdate',
2817 b'noupdate',
2816 None,
2818 None,
2817 _(b'do not update the new working directories'),
2819 _(b'do not update the new working directories'),
2818 ),
2820 ),
2819 (
2821 (
2820 b'',
2822 b'',
2821 b'uncompressed',
2823 b'uncompressed',
2822 None,
2824 None,
2823 _(b'use uncompressed transfer (fast over LAN)'),
2825 _(b'use uncompressed transfer (fast over LAN)'),
2824 ),
2826 ),
2825 (
2827 (
2826 b'p',
2828 b'p',
2827 b'patches',
2829 b'patches',
2828 b'',
2830 b'',
2829 _(b'location of source patch repository'),
2831 _(b'location of source patch repository'),
2830 _(b'REPO'),
2832 _(b'REPO'),
2831 ),
2833 ),
2832 ]
2834 ]
2833 + cmdutil.remoteopts,
2835 + cmdutil.remoteopts,
2834 _(b'hg qclone [OPTION]... SOURCE [DEST]'),
2836 _(b'hg qclone [OPTION]... SOURCE [DEST]'),
2835 helpcategory=command.CATEGORY_REPO_CREATION,
2837 helpcategory=command.CATEGORY_REPO_CREATION,
2836 norepo=True,
2838 norepo=True,
2837 )
2839 )
2838 def clone(ui, source, dest=None, **opts):
2840 def clone(ui, source, dest=None, **opts):
2839 """clone main and patch repository at same time
2841 """clone main and patch repository at same time
2840
2842
2841 If source is local, destination will have no patches applied. If
2843 If source is local, destination will have no patches applied. If
2842 source is remote, this command can not check if patches are
2844 source is remote, this command can not check if patches are
2843 applied in source, so cannot guarantee that patches are not
2845 applied in source, so cannot guarantee that patches are not
2844 applied in destination. If you clone remote repository, be sure
2846 applied in destination. If you clone remote repository, be sure
2845 before that it has no patches applied.
2847 before that it has no patches applied.
2846
2848
2847 Source patch repository is looked for in <src>/.hg/patches by
2849 Source patch repository is looked for in <src>/.hg/patches by
2848 default. Use -p <url> to change.
2850 default. Use -p <url> to change.
2849
2851
2850 The patch directory must be a nested Mercurial repository, as
2852 The patch directory must be a nested Mercurial repository, as
2851 would be created by :hg:`init --mq`.
2853 would be created by :hg:`init --mq`.
2852
2854
2853 Return 0 on success.
2855 Return 0 on success.
2854 """
2856 """
2855 opts = pycompat.byteskwargs(opts)
2857 opts = pycompat.byteskwargs(opts)
2856
2858
2857 def patchdir(repo):
2859 def patchdir(repo):
2858 """compute a patch repo url from a repo object"""
2860 """compute a patch repo url from a repo object"""
2859 url = repo.url()
2861 url = repo.url()
2860 if url.endswith(b'/'):
2862 if url.endswith(b'/'):
2861 url = url[:-1]
2863 url = url[:-1]
2862 return url + b'/.hg/patches'
2864 return url + b'/.hg/patches'
2863
2865
2864 # main repo (destination and sources)
2866 # main repo (destination and sources)
2865 if dest is None:
2867 if dest is None:
2866 dest = hg.defaultdest(source)
2868 dest = hg.defaultdest(source)
2867 __, source_path, __ = urlutil.get_clone_path(ui, source)
2869 __, source_path, __ = urlutil.get_clone_path(ui, source)
2868 sr = hg.peer(ui, opts, source_path)
2870 sr = hg.peer(ui, opts, source_path)
2869
2871
2870 # patches repo (source only)
2872 # patches repo (source only)
2871 if opts.get(b'patches'):
2873 if opts.get(b'patches'):
2872 __, patchespath, __ = urlutil.get_clone_path(ui, opts.get(b'patches'))
2874 __, patchespath, __ = urlutil.get_clone_path(ui, opts.get(b'patches'))
2873 else:
2875 else:
2874 patchespath = patchdir(sr)
2876 patchespath = patchdir(sr)
2875 try:
2877 try:
2876 hg.peer(ui, opts, patchespath)
2878 hg.peer(ui, opts, patchespath)
2877 except error.RepoError:
2879 except error.RepoError:
2878 raise error.Abort(
2880 raise error.Abort(
2879 _(b'versioned patch repository not found (see init --mq)')
2881 _(b'versioned patch repository not found (see init --mq)')
2880 )
2882 )
2881 qbase, destrev = None, None
2883 qbase, destrev = None, None
2882 if sr.local():
2884 if sr.local():
2883 repo = sr.local()
2885 repo = sr.local()
2884 if repo.mq.applied and repo[qbase].phase() != phases.secret:
2886 if repo.mq.applied and repo[qbase].phase() != phases.secret:
2885 qbase = repo.mq.applied[0].node
2887 qbase = repo.mq.applied[0].node
2886 if not hg.islocal(dest):
2888 if not hg.islocal(dest):
2887 heads = set(repo.heads())
2889 heads = set(repo.heads())
2888 destrev = list(heads.difference(repo.heads(qbase)))
2890 destrev = list(heads.difference(repo.heads(qbase)))
2889 destrev.append(repo.changelog.parents(qbase)[0])
2891 destrev.append(repo.changelog.parents(qbase)[0])
2890 elif sr.capable(b'lookup'):
2892 elif sr.capable(b'lookup'):
2891 try:
2893 try:
2892 qbase = sr.lookup(b'qbase')
2894 qbase = sr.lookup(b'qbase')
2893 except error.RepoError:
2895 except error.RepoError:
2894 pass
2896 pass
2895
2897
2896 ui.note(_(b'cloning main repository\n'))
2898 ui.note(_(b'cloning main repository\n'))
2897 sr, dr = hg.clone(
2899 sr, dr = hg.clone(
2898 ui,
2900 ui,
2899 opts,
2901 opts,
2900 sr.url(),
2902 sr.url(),
2901 dest,
2903 dest,
2902 pull=opts.get(b'pull'),
2904 pull=opts.get(b'pull'),
2903 revs=destrev,
2905 revs=destrev,
2904 update=False,
2906 update=False,
2905 stream=opts.get(b'uncompressed'),
2907 stream=opts.get(b'uncompressed'),
2906 )
2908 )
2907
2909
2908 ui.note(_(b'cloning patch repository\n'))
2910 ui.note(_(b'cloning patch repository\n'))
2909 hg.clone(
2911 hg.clone(
2910 ui,
2912 ui,
2911 opts,
2913 opts,
2912 opts.get(b'patches') or patchdir(sr),
2914 opts.get(b'patches') or patchdir(sr),
2913 patchdir(dr),
2915 patchdir(dr),
2914 pull=opts.get(b'pull'),
2916 pull=opts.get(b'pull'),
2915 update=not opts.get(b'noupdate'),
2917 update=not opts.get(b'noupdate'),
2916 stream=opts.get(b'uncompressed'),
2918 stream=opts.get(b'uncompressed'),
2917 )
2919 )
2918
2920
2919 if dr.local():
2921 if dr.local():
2920 repo = dr.local()
2922 repo = dr.local()
2921 if qbase:
2923 if qbase:
2922 ui.note(
2924 ui.note(
2923 _(
2925 _(
2924 b'stripping applied patches from destination '
2926 b'stripping applied patches from destination '
2925 b'repository\n'
2927 b'repository\n'
2926 )
2928 )
2927 )
2929 )
2928 strip(ui, repo, [qbase], update=False, backup=None)
2930 strip(ui, repo, [qbase], update=False, backup=None)
2929 if not opts.get(b'noupdate'):
2931 if not opts.get(b'noupdate'):
2930 ui.note(_(b'updating destination repository\n'))
2932 ui.note(_(b'updating destination repository\n'))
2931 hg.update(repo, repo.changelog.tip())
2933 hg.update(repo, repo.changelog.tip())
2932
2934
2933
2935
2934 @command(
2936 @command(
2935 b"qcommit|qci",
2937 b"qcommit|qci",
2936 commands.table[b"commit|ci"][1],
2938 commands.table[b"commit|ci"][1],
2937 _(b'hg qcommit [OPTION]... [FILE]...'),
2939 _(b'hg qcommit [OPTION]... [FILE]...'),
2938 helpcategory=command.CATEGORY_COMMITTING,
2940 helpcategory=command.CATEGORY_COMMITTING,
2939 inferrepo=True,
2941 inferrepo=True,
2940 )
2942 )
2941 def commit(ui, repo, *pats, **opts):
2943 def commit(ui, repo, *pats, **opts):
2942 """commit changes in the queue repository (DEPRECATED)
2944 """commit changes in the queue repository (DEPRECATED)
2943
2945
2944 This command is deprecated; use :hg:`commit --mq` instead."""
2946 This command is deprecated; use :hg:`commit --mq` instead."""
2945 q = repo.mq
2947 q = repo.mq
2946 r = q.qrepo()
2948 r = q.qrepo()
2947 if not r:
2949 if not r:
2948 raise error.Abort(b'no queue repository')
2950 raise error.Abort(b'no queue repository')
2949 commands.commit(r.ui, r, *pats, **opts)
2951 commands.commit(r.ui, r, *pats, **opts)
2950
2952
2951
2953
2952 @command(
2954 @command(
2953 b"qseries",
2955 b"qseries",
2954 [
2956 [
2955 (b'm', b'missing', None, _(b'print patches not in series')),
2957 (b'm', b'missing', None, _(b'print patches not in series')),
2956 ]
2958 ]
2957 + seriesopts,
2959 + seriesopts,
2958 _(b'hg qseries [-ms]'),
2960 _(b'hg qseries [-ms]'),
2959 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2961 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2960 )
2962 )
2961 def series(ui, repo, **opts):
2963 def series(ui, repo, **opts):
2962 """print the entire series file
2964 """print the entire series file
2963
2965
2964 Returns 0 on success."""
2966 Returns 0 on success."""
2965 repo.mq.qseries(
2967 repo.mq.qseries(
2966 repo, missing=opts.get('missing'), summary=opts.get('summary')
2968 repo, missing=opts.get('missing'), summary=opts.get('summary')
2967 )
2969 )
2968 return 0
2970 return 0
2969
2971
2970
2972
2971 @command(
2973 @command(
2972 b"qtop",
2974 b"qtop",
2973 seriesopts,
2975 seriesopts,
2974 _(b'hg qtop [-s]'),
2976 _(b'hg qtop [-s]'),
2975 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2977 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2976 )
2978 )
2977 def top(ui, repo, **opts):
2979 def top(ui, repo, **opts):
2978 """print the name of the current patch
2980 """print the name of the current patch
2979
2981
2980 Returns 0 on success."""
2982 Returns 0 on success."""
2981 q = repo.mq
2983 q = repo.mq
2982 if q.applied:
2984 if q.applied:
2983 t = q.seriesend(True)
2985 t = q.seriesend(True)
2984 else:
2986 else:
2985 t = 0
2987 t = 0
2986
2988
2987 if t:
2989 if t:
2988 q.qseries(
2990 q.qseries(
2989 repo,
2991 repo,
2990 start=t - 1,
2992 start=t - 1,
2991 length=1,
2993 length=1,
2992 status=b'A',
2994 status=b'A',
2993 summary=opts.get('summary'),
2995 summary=opts.get('summary'),
2994 )
2996 )
2995 else:
2997 else:
2996 ui.write(_(b"no patches applied\n"))
2998 ui.write(_(b"no patches applied\n"))
2997 return 1
2999 return 1
2998
3000
2999
3001
3000 @command(
3002 @command(
3001 b"qnext",
3003 b"qnext",
3002 seriesopts,
3004 seriesopts,
3003 _(b'hg qnext [-s]'),
3005 _(b'hg qnext [-s]'),
3004 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3006 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3005 )
3007 )
3006 def next(ui, repo, **opts):
3008 def next(ui, repo, **opts):
3007 """print the name of the next pushable patch
3009 """print the name of the next pushable patch
3008
3010
3009 Returns 0 on success."""
3011 Returns 0 on success."""
3010 q = repo.mq
3012 q = repo.mq
3011 end = q.seriesend()
3013 end = q.seriesend()
3012 if end == len(q.series):
3014 if end == len(q.series):
3013 ui.write(_(b"all patches applied\n"))
3015 ui.write(_(b"all patches applied\n"))
3014 return 1
3016 return 1
3015 q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
3017 q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
3016
3018
3017
3019
3018 @command(
3020 @command(
3019 b"qprev",
3021 b"qprev",
3020 seriesopts,
3022 seriesopts,
3021 _(b'hg qprev [-s]'),
3023 _(b'hg qprev [-s]'),
3022 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3024 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3023 )
3025 )
3024 def prev(ui, repo, **opts):
3026 def prev(ui, repo, **opts):
3025 """print the name of the preceding applied patch
3027 """print the name of the preceding applied patch
3026
3028
3027 Returns 0 on success."""
3029 Returns 0 on success."""
3028 q = repo.mq
3030 q = repo.mq
3029 l = len(q.applied)
3031 l = len(q.applied)
3030 if l == 1:
3032 if l == 1:
3031 ui.write(_(b"only one patch applied\n"))
3033 ui.write(_(b"only one patch applied\n"))
3032 return 1
3034 return 1
3033 if not l:
3035 if not l:
3034 ui.write(_(b"no patches applied\n"))
3036 ui.write(_(b"no patches applied\n"))
3035 return 1
3037 return 1
3036 idx = q.series.index(q.applied[-2].name)
3038 idx = q.series.index(q.applied[-2].name)
3037 q.qseries(
3039 q.qseries(
3038 repo, start=idx, length=1, status=b'A', summary=opts.get('summary')
3040 repo, start=idx, length=1, status=b'A', summary=opts.get('summary')
3039 )
3041 )
3040
3042
3041
3043
3042 def setupheaderopts(ui, opts):
3044 def setupheaderopts(ui, opts):
3043 if not opts.get(b'user') and opts.get(b'currentuser'):
3045 if not opts.get(b'user') and opts.get(b'currentuser'):
3044 opts[b'user'] = ui.username()
3046 opts[b'user'] = ui.username()
3045 if not opts.get(b'date') and opts.get(b'currentdate'):
3047 if not opts.get(b'date') and opts.get(b'currentdate'):
3046 opts[b'date'] = b"%d %d" % dateutil.makedate()
3048 opts[b'date'] = b"%d %d" % dateutil.makedate()
3047
3049
3048
3050
3049 @command(
3051 @command(
3050 b"qnew",
3052 b"qnew",
3051 [
3053 [
3052 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
3054 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
3053 (b'f', b'force', None, _(b'import uncommitted changes (DEPRECATED)')),
3055 (b'f', b'force', None, _(b'import uncommitted changes (DEPRECATED)')),
3054 (b'g', b'git', None, _(b'use git extended diff format')),
3056 (b'g', b'git', None, _(b'use git extended diff format')),
3055 (b'U', b'currentuser', None, _(b'add "From: <current user>" to patch')),
3057 (b'U', b'currentuser', None, _(b'add "From: <current user>" to patch')),
3056 (b'u', b'user', b'', _(b'add "From: <USER>" to patch'), _(b'USER')),
3058 (b'u', b'user', b'', _(b'add "From: <USER>" to patch'), _(b'USER')),
3057 (b'D', b'currentdate', None, _(b'add "Date: <current date>" to patch')),
3059 (b'D', b'currentdate', None, _(b'add "Date: <current date>" to patch')),
3058 (b'd', b'date', b'', _(b'add "Date: <DATE>" to patch'), _(b'DATE')),
3060 (b'd', b'date', b'', _(b'add "Date: <DATE>" to patch'), _(b'DATE')),
3059 ]
3061 ]
3060 + cmdutil.walkopts
3062 + cmdutil.walkopts
3061 + cmdutil.commitopts,
3063 + cmdutil.commitopts,
3062 _(b'hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'),
3064 _(b'hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'),
3063 helpcategory=command.CATEGORY_COMMITTING,
3065 helpcategory=command.CATEGORY_COMMITTING,
3064 helpbasic=True,
3066 helpbasic=True,
3065 inferrepo=True,
3067 inferrepo=True,
3066 )
3068 )
3067 def new(ui, repo, patch, *args, **opts):
3069 def new(ui, repo, patch, *args, **opts):
3068 """create a new patch
3070 """create a new patch
3069
3071
3070 qnew creates a new patch on top of the currently-applied patch (if
3072 qnew creates a new patch on top of the currently-applied patch (if
3071 any). The patch will be initialized with any outstanding changes
3073 any). The patch will be initialized with any outstanding changes
3072 in the working directory. You may also use -I/--include,
3074 in the working directory. You may also use -I/--include,
3073 -X/--exclude, and/or a list of files after the patch name to add
3075 -X/--exclude, and/or a list of files after the patch name to add
3074 only changes to matching files to the new patch, leaving the rest
3076 only changes to matching files to the new patch, leaving the rest
3075 as uncommitted modifications.
3077 as uncommitted modifications.
3076
3078
3077 -u/--user and -d/--date can be used to set the (given) user and
3079 -u/--user and -d/--date can be used to set the (given) user and
3078 date, respectively. -U/--currentuser and -D/--currentdate set user
3080 date, respectively. -U/--currentuser and -D/--currentdate set user
3079 to current user and date to current date.
3081 to current user and date to current date.
3080
3082
3081 -e/--edit, -m/--message or -l/--logfile set the patch header as
3083 -e/--edit, -m/--message or -l/--logfile set the patch header as
3082 well as the commit message. If none is specified, the header is
3084 well as the commit message. If none is specified, the header is
3083 empty and the commit message is '[mq]: PATCH'.
3085 empty and the commit message is '[mq]: PATCH'.
3084
3086
3085 Use the -g/--git option to keep the patch in the git extended diff
3087 Use the -g/--git option to keep the patch in the git extended diff
3086 format. Read the diffs help topic for more information on why this
3088 format. Read the diffs help topic for more information on why this
3087 is important for preserving permission changes and copy/rename
3089 is important for preserving permission changes and copy/rename
3088 information.
3090 information.
3089
3091
3090 Returns 0 on successful creation of a new patch.
3092 Returns 0 on successful creation of a new patch.
3091 """
3093 """
3092 opts = pycompat.byteskwargs(opts)
3094 opts = pycompat.byteskwargs(opts)
3093 msg = cmdutil.logmessage(ui, opts)
3095 msg = cmdutil.logmessage(ui, opts)
3094 q = repo.mq
3096 q = repo.mq
3095 opts[b'msg'] = msg
3097 opts[b'msg'] = msg
3096 setupheaderopts(ui, opts)
3098 setupheaderopts(ui, opts)
3097 q.new(repo, patch, *args, **pycompat.strkwargs(opts))
3099 q.new(repo, patch, *args, **pycompat.strkwargs(opts))
3098 q.savedirty()
3100 q.savedirty()
3099 return 0
3101 return 0
3100
3102
3101
3103
3102 @command(
3104 @command(
3103 b"qrefresh",
3105 b"qrefresh",
3104 [
3106 [
3105 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
3107 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
3106 (b'g', b'git', None, _(b'use git extended diff format')),
3108 (b'g', b'git', None, _(b'use git extended diff format')),
3107 (
3109 (
3108 b's',
3110 b's',
3109 b'short',
3111 b'short',
3110 None,
3112 None,
3111 _(b'refresh only files already in the patch and specified files'),
3113 _(b'refresh only files already in the patch and specified files'),
3112 ),
3114 ),
3113 (
3115 (
3114 b'U',
3116 b'U',
3115 b'currentuser',
3117 b'currentuser',
3116 None,
3118 None,
3117 _(b'add/update author field in patch with current user'),
3119 _(b'add/update author field in patch with current user'),
3118 ),
3120 ),
3119 (
3121 (
3120 b'u',
3122 b'u',
3121 b'user',
3123 b'user',
3122 b'',
3124 b'',
3123 _(b'add/update author field in patch with given user'),
3125 _(b'add/update author field in patch with given user'),
3124 _(b'USER'),
3126 _(b'USER'),
3125 ),
3127 ),
3126 (
3128 (
3127 b'D',
3129 b'D',
3128 b'currentdate',
3130 b'currentdate',
3129 None,
3131 None,
3130 _(b'add/update date field in patch with current date'),
3132 _(b'add/update date field in patch with current date'),
3131 ),
3133 ),
3132 (
3134 (
3133 b'd',
3135 b'd',
3134 b'date',
3136 b'date',
3135 b'',
3137 b'',
3136 _(b'add/update date field in patch with given date'),
3138 _(b'add/update date field in patch with given date'),
3137 _(b'DATE'),
3139 _(b'DATE'),
3138 ),
3140 ),
3139 ]
3141 ]
3140 + cmdutil.walkopts
3142 + cmdutil.walkopts
3141 + cmdutil.commitopts,
3143 + cmdutil.commitopts,
3142 _(b'hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'),
3144 _(b'hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'),
3143 helpcategory=command.CATEGORY_COMMITTING,
3145 helpcategory=command.CATEGORY_COMMITTING,
3144 helpbasic=True,
3146 helpbasic=True,
3145 inferrepo=True,
3147 inferrepo=True,
3146 )
3148 )
3147 def refresh(ui, repo, *pats, **opts):
3149 def refresh(ui, repo, *pats, **opts):
3148 """update the current patch
3150 """update the current patch
3149
3151
3150 If any file patterns are provided, the refreshed patch will
3152 If any file patterns are provided, the refreshed patch will
3151 contain only the modifications that match those patterns; the
3153 contain only the modifications that match those patterns; the
3152 remaining modifications will remain in the working directory.
3154 remaining modifications will remain in the working directory.
3153
3155
3154 If -s/--short is specified, files currently included in the patch
3156 If -s/--short is specified, files currently included in the patch
3155 will be refreshed just like matched files and remain in the patch.
3157 will be refreshed just like matched files and remain in the patch.
3156
3158
3157 If -e/--edit is specified, Mercurial will start your configured editor for
3159 If -e/--edit is specified, Mercurial will start your configured editor for
3158 you to enter a message. In case qrefresh fails, you will find a backup of
3160 you to enter a message. In case qrefresh fails, you will find a backup of
3159 your message in ``.hg/last-message.txt``.
3161 your message in ``.hg/last-message.txt``.
3160
3162
3161 hg add/remove/copy/rename work as usual, though you might want to
3163 hg add/remove/copy/rename work as usual, though you might want to
3162 use git-style patches (-g/--git or [diff] git=1) to track copies
3164 use git-style patches (-g/--git or [diff] git=1) to track copies
3163 and renames. See the diffs help topic for more information on the
3165 and renames. See the diffs help topic for more information on the
3164 git diff format.
3166 git diff format.
3165
3167
3166 Returns 0 on success.
3168 Returns 0 on success.
3167 """
3169 """
3168 opts = pycompat.byteskwargs(opts)
3170 opts = pycompat.byteskwargs(opts)
3169 q = repo.mq
3171 q = repo.mq
3170 message = cmdutil.logmessage(ui, opts)
3172 message = cmdutil.logmessage(ui, opts)
3171 setupheaderopts(ui, opts)
3173 setupheaderopts(ui, opts)
3172 with repo.wlock():
3174 with repo.wlock():
3173 ret = q.refresh(repo, pats, msg=message, **pycompat.strkwargs(opts))
3175 ret = q.refresh(repo, pats, msg=message, **pycompat.strkwargs(opts))
3174 q.savedirty()
3176 q.savedirty()
3175 return ret
3177 return ret
3176
3178
3177
3179
3178 @command(
3180 @command(
3179 b"qdiff",
3181 b"qdiff",
3180 cmdutil.diffopts + cmdutil.diffopts2 + cmdutil.walkopts,
3182 cmdutil.diffopts + cmdutil.diffopts2 + cmdutil.walkopts,
3181 _(b'hg qdiff [OPTION]... [FILE]...'),
3183 _(b'hg qdiff [OPTION]... [FILE]...'),
3182 helpcategory=command.CATEGORY_FILE_CONTENTS,
3184 helpcategory=command.CATEGORY_FILE_CONTENTS,
3183 helpbasic=True,
3185 helpbasic=True,
3184 inferrepo=True,
3186 inferrepo=True,
3185 )
3187 )
3186 def diff(ui, repo, *pats, **opts):
3188 def diff(ui, repo, *pats, **opts):
3187 """diff of the current patch and subsequent modifications
3189 """diff of the current patch and subsequent modifications
3188
3190
3189 Shows a diff which includes the current patch as well as any
3191 Shows a diff which includes the current patch as well as any
3190 changes which have been made in the working directory since the
3192 changes which have been made in the working directory since the
3191 last refresh (thus showing what the current patch would become
3193 last refresh (thus showing what the current patch would become
3192 after a qrefresh).
3194 after a qrefresh).
3193
3195
3194 Use :hg:`diff` if you only want to see the changes made since the
3196 Use :hg:`diff` if you only want to see the changes made since the
3195 last qrefresh, or :hg:`export qtip` if you want to see changes
3197 last qrefresh, or :hg:`export qtip` if you want to see changes
3196 made by the current patch without including changes made since the
3198 made by the current patch without including changes made since the
3197 qrefresh.
3199 qrefresh.
3198
3200
3199 Returns 0 on success.
3201 Returns 0 on success.
3200 """
3202 """
3201 ui.pager(b'qdiff')
3203 ui.pager(b'qdiff')
3202 repo.mq.diff(repo, pats, pycompat.byteskwargs(opts))
3204 repo.mq.diff(repo, pats, pycompat.byteskwargs(opts))
3203 return 0
3205 return 0
3204
3206
3205
3207
3206 @command(
3208 @command(
3207 b'qfold',
3209 b'qfold',
3208 [
3210 [
3209 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
3211 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
3210 (b'k', b'keep', None, _(b'keep folded patch files')),
3212 (b'k', b'keep', None, _(b'keep folded patch files')),
3211 ]
3213 ]
3212 + cmdutil.commitopts,
3214 + cmdutil.commitopts,
3213 _(b'hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'),
3215 _(b'hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'),
3214 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
3216 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
3215 )
3217 )
3216 def fold(ui, repo, *files, **opts):
3218 def fold(ui, repo, *files, **opts):
3217 """fold the named patches into the current patch
3219 """fold the named patches into the current patch
3218
3220
3219 Patches must not yet be applied. Each patch will be successively
3221 Patches must not yet be applied. Each patch will be successively
3220 applied to the current patch in the order given. If all the
3222 applied to the current patch in the order given. If all the
3221 patches apply successfully, the current patch will be refreshed
3223 patches apply successfully, the current patch will be refreshed
3222 with the new cumulative patch, and the folded patches will be
3224 with the new cumulative patch, and the folded patches will be
3223 deleted. With -k/--keep, the folded patch files will not be
3225 deleted. With -k/--keep, the folded patch files will not be
3224 removed afterwards.
3226 removed afterwards.
3225
3227
3226 The header for each folded patch will be concatenated with the
3228 The header for each folded patch will be concatenated with the
3227 current patch header, separated by a line of ``* * *``.
3229 current patch header, separated by a line of ``* * *``.
3228
3230
3229 Returns 0 on success."""
3231 Returns 0 on success."""
3230 opts = pycompat.byteskwargs(opts)
3232 opts = pycompat.byteskwargs(opts)
3231 q = repo.mq
3233 q = repo.mq
3232 if not files:
3234 if not files:
3233 raise error.Abort(_(b'qfold requires at least one patch name'))
3235 raise error.Abort(_(b'qfold requires at least one patch name'))
3234 if not q.checktoppatch(repo)[0]:
3236 if not q.checktoppatch(repo)[0]:
3235 raise error.Abort(_(b'no patches applied'))
3237 raise error.Abort(_(b'no patches applied'))
3236 q.checklocalchanges(repo)
3238 q.checklocalchanges(repo)
3237
3239
3238 message = cmdutil.logmessage(ui, opts)
3240 message = cmdutil.logmessage(ui, opts)
3239
3241
3240 parent = q.lookup(b'qtip')
3242 parent = q.lookup(b'qtip')
3241 patches = []
3243 patches = []
3242 messages = []
3244 messages = []
3243 for f in files:
3245 for f in files:
3244 p = q.lookup(f)
3246 p = q.lookup(f)
3245 if p in patches or p == parent:
3247 if p in patches or p == parent:
3246 ui.warn(_(b'skipping already folded patch %s\n') % p)
3248 ui.warn(_(b'skipping already folded patch %s\n') % p)
3247 if q.isapplied(p):
3249 if q.isapplied(p):
3248 raise error.Abort(
3250 raise error.Abort(
3249 _(b'qfold cannot fold already applied patch %s') % p
3251 _(b'qfold cannot fold already applied patch %s') % p
3250 )
3252 )
3251 patches.append(p)
3253 patches.append(p)
3252
3254
3253 for p in patches:
3255 for p in patches:
3254 if not message:
3256 if not message:
3255 ph = patchheader(q.join(p), q.plainmode)
3257 ph = patchheader(q.join(p), q.plainmode)
3256 if ph.message:
3258 if ph.message:
3257 messages.append(ph.message)
3259 messages.append(ph.message)
3258 pf = q.join(p)
3260 pf = q.join(p)
3259 (patchsuccess, files, fuzz) = q.patch(repo, pf)
3261 (patchsuccess, files, fuzz) = q.patch(repo, pf)
3260 if not patchsuccess:
3262 if not patchsuccess:
3261 raise error.Abort(_(b'error folding patch %s') % p)
3263 raise error.Abort(_(b'error folding patch %s') % p)
3262
3264
3263 if not message:
3265 if not message:
3264 ph = patchheader(q.join(parent), q.plainmode)
3266 ph = patchheader(q.join(parent), q.plainmode)
3265 message = ph.message
3267 message = ph.message
3266 for msg in messages:
3268 for msg in messages:
3267 if msg:
3269 if msg:
3268 if message:
3270 if message:
3269 message.append(b'* * *')
3271 message.append(b'* * *')
3270 message.extend(msg)
3272 message.extend(msg)
3271 message = b'\n'.join(message)
3273 message = b'\n'.join(message)
3272
3274
3273 diffopts = q.patchopts(q.diffopts(), *patches)
3275 diffopts = q.patchopts(q.diffopts(), *patches)
3274 with repo.wlock():
3276 with repo.wlock():
3275 q.refresh(
3277 q.refresh(
3276 repo,
3278 repo,
3277 msg=message,
3279 msg=message,
3278 git=diffopts.git,
3280 git=diffopts.git,
3279 edit=opts.get(b'edit'),
3281 edit=opts.get(b'edit'),
3280 editform=b'mq.qfold',
3282 editform=b'mq.qfold',
3281 )
3283 )
3282 q.delete(repo, patches, opts)
3284 q.delete(repo, patches, opts)
3283 q.savedirty()
3285 q.savedirty()
3284
3286
3285
3287
3286 @command(
3288 @command(
3287 b"qgoto",
3289 b"qgoto",
3288 [
3290 [
3289 (
3291 (
3290 b'',
3292 b'',
3291 b'keep-changes',
3293 b'keep-changes',
3292 None,
3294 None,
3293 _(b'tolerate non-conflicting local changes'),
3295 _(b'tolerate non-conflicting local changes'),
3294 ),
3296 ),
3295 (b'f', b'force', None, _(b'overwrite any local changes')),
3297 (b'f', b'force', None, _(b'overwrite any local changes')),
3296 (b'', b'no-backup', None, _(b'do not save backup copies of files')),
3298 (b'', b'no-backup', None, _(b'do not save backup copies of files')),
3297 ],
3299 ],
3298 _(b'hg qgoto [OPTION]... PATCH'),
3300 _(b'hg qgoto [OPTION]... PATCH'),
3299 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3301 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3300 )
3302 )
3301 def goto(ui, repo, patch, **opts):
3303 def goto(ui, repo, patch, **opts):
3302 """push or pop patches until named patch is at top of stack
3304 """push or pop patches until named patch is at top of stack
3303
3305
3304 Returns 0 on success."""
3306 Returns 0 on success."""
3305 opts = pycompat.byteskwargs(opts)
3307 opts = pycompat.byteskwargs(opts)
3306 opts = fixkeepchangesopts(ui, opts)
3308 opts = fixkeepchangesopts(ui, opts)
3307 q = repo.mq
3309 q = repo.mq
3308 patch = q.lookup(patch)
3310 patch = q.lookup(patch)
3309 nobackup = opts.get(b'no_backup')
3311 nobackup = opts.get(b'no_backup')
3310 keepchanges = opts.get(b'keep_changes')
3312 keepchanges = opts.get(b'keep_changes')
3311 if q.isapplied(patch):
3313 if q.isapplied(patch):
3312 ret = q.pop(
3314 ret = q.pop(
3313 repo,
3315 repo,
3314 patch,
3316 patch,
3315 force=opts.get(b'force'),
3317 force=opts.get(b'force'),
3316 nobackup=nobackup,
3318 nobackup=nobackup,
3317 keepchanges=keepchanges,
3319 keepchanges=keepchanges,
3318 )
3320 )
3319 else:
3321 else:
3320 ret = q.push(
3322 ret = q.push(
3321 repo,
3323 repo,
3322 patch,
3324 patch,
3323 force=opts.get(b'force'),
3325 force=opts.get(b'force'),
3324 nobackup=nobackup,
3326 nobackup=nobackup,
3325 keepchanges=keepchanges,
3327 keepchanges=keepchanges,
3326 )
3328 )
3327 q.savedirty()
3329 q.savedirty()
3328 return ret
3330 return ret
3329
3331
3330
3332
3331 @command(
3333 @command(
3332 b"qguard",
3334 b"qguard",
3333 [
3335 [
3334 (b'l', b'list', None, _(b'list all patches and guards')),
3336 (b'l', b'list', None, _(b'list all patches and guards')),
3335 (b'n', b'none', None, _(b'drop all guards')),
3337 (b'n', b'none', None, _(b'drop all guards')),
3336 ],
3338 ],
3337 _(b'hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'),
3339 _(b'hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'),
3338 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3340 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3339 )
3341 )
3340 def guard(ui, repo, *args, **opts):
3342 def guard(ui, repo, *args, **opts):
3341 """set or print guards for a patch
3343 """set or print guards for a patch
3342
3344
3343 Guards control whether a patch can be pushed. A patch with no
3345 Guards control whether a patch can be pushed. A patch with no
3344 guards is always pushed. A patch with a positive guard ("+foo") is
3346 guards is always pushed. A patch with a positive guard ("+foo") is
3345 pushed only if the :hg:`qselect` command has activated it. A patch with
3347 pushed only if the :hg:`qselect` command has activated it. A patch with
3346 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
3348 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
3347 has activated it.
3349 has activated it.
3348
3350
3349 With no arguments, print the currently active guards.
3351 With no arguments, print the currently active guards.
3350 With arguments, set guards for the named patch.
3352 With arguments, set guards for the named patch.
3351
3353
3352 .. note::
3354 .. note::
3353
3355
3354 Specifying negative guards now requires '--'.
3356 Specifying negative guards now requires '--'.
3355
3357
3356 To set guards on another patch::
3358 To set guards on another patch::
3357
3359
3358 hg qguard other.patch -- +2.6.17 -stable
3360 hg qguard other.patch -- +2.6.17 -stable
3359
3361
3360 Returns 0 on success.
3362 Returns 0 on success.
3361 """
3363 """
3362
3364
3363 def status(idx):
3365 def status(idx):
3364 guards = q.seriesguards[idx] or [b'unguarded']
3366 guards = q.seriesguards[idx] or [b'unguarded']
3365 if q.series[idx] in applied:
3367 if q.series[idx] in applied:
3366 state = b'applied'
3368 state = b'applied'
3367 elif q.pushable(idx)[0]:
3369 elif q.pushable(idx)[0]:
3368 state = b'unapplied'
3370 state = b'unapplied'
3369 else:
3371 else:
3370 state = b'guarded'
3372 state = b'guarded'
3371 label = b'qguard.patch qguard.%s qseries.%s' % (state, state)
3373 label = b'qguard.patch qguard.%s qseries.%s' % (state, state)
3372 ui.write(b'%s: ' % ui.label(q.series[idx], label))
3374 ui.write(b'%s: ' % ui.label(q.series[idx], label))
3373
3375
3374 for i, guard in enumerate(guards):
3376 for i, guard in enumerate(guards):
3375 if guard.startswith(b'+'):
3377 if guard.startswith(b'+'):
3376 ui.write(guard, label=b'qguard.positive')
3378 ui.write(guard, label=b'qguard.positive')
3377 elif guard.startswith(b'-'):
3379 elif guard.startswith(b'-'):
3378 ui.write(guard, label=b'qguard.negative')
3380 ui.write(guard, label=b'qguard.negative')
3379 else:
3381 else:
3380 ui.write(guard, label=b'qguard.unguarded')
3382 ui.write(guard, label=b'qguard.unguarded')
3381 if i != len(guards) - 1:
3383 if i != len(guards) - 1:
3382 ui.write(b' ')
3384 ui.write(b' ')
3383 ui.write(b'\n')
3385 ui.write(b'\n')
3384
3386
3385 q = repo.mq
3387 q = repo.mq
3386 applied = {p.name for p in q.applied}
3388 applied = {p.name for p in q.applied}
3387 patch = None
3389 patch = None
3388 args = list(args)
3390 args = list(args)
3389 if opts.get('list'):
3391 if opts.get('list'):
3390 if args or opts.get('none'):
3392 if args or opts.get('none'):
3391 raise error.Abort(
3393 raise error.Abort(
3392 _(b'cannot mix -l/--list with options or arguments')
3394 _(b'cannot mix -l/--list with options or arguments')
3393 )
3395 )
3394 for i in pycompat.xrange(len(q.series)):
3396 for i in pycompat.xrange(len(q.series)):
3395 status(i)
3397 status(i)
3396 return
3398 return
3397 if not args or args[0][0:1] in b'-+':
3399 if not args or args[0][0:1] in b'-+':
3398 if not q.applied:
3400 if not q.applied:
3399 raise error.Abort(_(b'no patches applied'))
3401 raise error.Abort(_(b'no patches applied'))
3400 patch = q.applied[-1].name
3402 patch = q.applied[-1].name
3401 if patch is None and args[0][0:1] not in b'-+':
3403 if patch is None and args[0][0:1] not in b'-+':
3402 patch = args.pop(0)
3404 patch = args.pop(0)
3403 if patch is None:
3405 if patch is None:
3404 raise error.Abort(_(b'no patch to work with'))
3406 raise error.Abort(_(b'no patch to work with'))
3405 if args or opts.get('none'):
3407 if args or opts.get('none'):
3406 idx = q.findseries(patch)
3408 idx = q.findseries(patch)
3407 if idx is None:
3409 if idx is None:
3408 raise error.Abort(_(b'no patch named %s') % patch)
3410 raise error.Abort(_(b'no patch named %s') % patch)
3409 q.setguards(idx, args)
3411 q.setguards(idx, args)
3410 q.savedirty()
3412 q.savedirty()
3411 else:
3413 else:
3412 status(q.series.index(q.lookup(patch)))
3414 status(q.series.index(q.lookup(patch)))
3413
3415
3414
3416
3415 @command(
3417 @command(
3416 b"qheader",
3418 b"qheader",
3417 [],
3419 [],
3418 _(b'hg qheader [PATCH]'),
3420 _(b'hg qheader [PATCH]'),
3419 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3421 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3420 )
3422 )
3421 def header(ui, repo, patch=None):
3423 def header(ui, repo, patch=None):
3422 """print the header of the topmost or specified patch
3424 """print the header of the topmost or specified patch
3423
3425
3424 Returns 0 on success."""
3426 Returns 0 on success."""
3425 q = repo.mq
3427 q = repo.mq
3426
3428
3427 if patch:
3429 if patch:
3428 patch = q.lookup(patch)
3430 patch = q.lookup(patch)
3429 else:
3431 else:
3430 if not q.applied:
3432 if not q.applied:
3431 ui.write(_(b'no patches applied\n'))
3433 ui.write(_(b'no patches applied\n'))
3432 return 1
3434 return 1
3433 patch = q.lookup(b'qtip')
3435 patch = q.lookup(b'qtip')
3434 ph = patchheader(q.join(patch), q.plainmode)
3436 ph = patchheader(q.join(patch), q.plainmode)
3435
3437
3436 ui.write(b'\n'.join(ph.message) + b'\n')
3438 ui.write(b'\n'.join(ph.message) + b'\n')
3437
3439
3438
3440
3439 def lastsavename(path):
3441 def lastsavename(path):
3440 (directory, base) = os.path.split(path)
3442 (directory, base) = os.path.split(path)
3441 names = os.listdir(directory)
3443 names = os.listdir(directory)
3442 namere = re.compile(b"%s.([0-9]+)" % base)
3444 namere = re.compile(b"%s.([0-9]+)" % base)
3443 maxindex = None
3445 maxindex = None
3444 maxname = None
3446 maxname = None
3445 for f in names:
3447 for f in names:
3446 m = namere.match(f)
3448 m = namere.match(f)
3447 if m:
3449 if m:
3448 index = int(m.group(1))
3450 index = int(m.group(1))
3449 if maxindex is None or index > maxindex:
3451 if maxindex is None or index > maxindex:
3450 maxindex = index
3452 maxindex = index
3451 maxname = f
3453 maxname = f
3452 if maxname:
3454 if maxname:
3453 return (os.path.join(directory, maxname), maxindex)
3455 return (os.path.join(directory, maxname), maxindex)
3454 return (None, None)
3456 return (None, None)
3455
3457
3456
3458
3457 def savename(path):
3459 def savename(path):
3458 (last, index) = lastsavename(path)
3460 (last, index) = lastsavename(path)
3459 if last is None:
3461 if last is None:
3460 index = 0
3462 index = 0
3461 newpath = path + b".%d" % (index + 1)
3463 newpath = path + b".%d" % (index + 1)
3462 return newpath
3464 return newpath
3463
3465
3464
3466
3465 @command(
3467 @command(
3466 b"qpush",
3468 b"qpush",
3467 [
3469 [
3468 (
3470 (
3469 b'',
3471 b'',
3470 b'keep-changes',
3472 b'keep-changes',
3471 None,
3473 None,
3472 _(b'tolerate non-conflicting local changes'),
3474 _(b'tolerate non-conflicting local changes'),
3473 ),
3475 ),
3474 (b'f', b'force', None, _(b'apply on top of local changes')),
3476 (b'f', b'force', None, _(b'apply on top of local changes')),
3475 (
3477 (
3476 b'e',
3478 b'e',
3477 b'exact',
3479 b'exact',
3478 None,
3480 None,
3479 _(b'apply the target patch to its recorded parent'),
3481 _(b'apply the target patch to its recorded parent'),
3480 ),
3482 ),
3481 (b'l', b'list', None, _(b'list patch name in commit text')),
3483 (b'l', b'list', None, _(b'list patch name in commit text')),
3482 (b'a', b'all', None, _(b'apply all patches')),
3484 (b'a', b'all', None, _(b'apply all patches')),
3483 (b'm', b'merge', None, _(b'merge from another queue (DEPRECATED)')),
3485 (b'm', b'merge', None, _(b'merge from another queue (DEPRECATED)')),
3484 (b'n', b'name', b'', _(b'merge queue name (DEPRECATED)'), _(b'NAME')),
3486 (b'n', b'name', b'', _(b'merge queue name (DEPRECATED)'), _(b'NAME')),
3485 (
3487 (
3486 b'',
3488 b'',
3487 b'move',
3489 b'move',
3488 None,
3490 None,
3489 _(b'reorder patch series and apply only the patch'),
3491 _(b'reorder patch series and apply only the patch'),
3490 ),
3492 ),
3491 (b'', b'no-backup', None, _(b'do not save backup copies of files')),
3493 (b'', b'no-backup', None, _(b'do not save backup copies of files')),
3492 ],
3494 ],
3493 _(b'hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'),
3495 _(b'hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'),
3494 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3496 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3495 helpbasic=True,
3497 helpbasic=True,
3496 )
3498 )
3497 def push(ui, repo, patch=None, **opts):
3499 def push(ui, repo, patch=None, **opts):
3498 """push the next patch onto the stack
3500 """push the next patch onto the stack
3499
3501
3500 By default, abort if the working directory contains uncommitted
3502 By default, abort if the working directory contains uncommitted
3501 changes. With --keep-changes, abort only if the uncommitted files
3503 changes. With --keep-changes, abort only if the uncommitted files
3502 overlap with patched files. With -f/--force, backup and patch over
3504 overlap with patched files. With -f/--force, backup and patch over
3503 uncommitted changes.
3505 uncommitted changes.
3504
3506
3505 Return 0 on success.
3507 Return 0 on success.
3506 """
3508 """
3507 q = repo.mq
3509 q = repo.mq
3508 mergeq = None
3510 mergeq = None
3509
3511
3510 opts = pycompat.byteskwargs(opts)
3512 opts = pycompat.byteskwargs(opts)
3511 opts = fixkeepchangesopts(ui, opts)
3513 opts = fixkeepchangesopts(ui, opts)
3512 if opts.get(b'merge'):
3514 if opts.get(b'merge'):
3513 if opts.get(b'name'):
3515 if opts.get(b'name'):
3514 newpath = repo.vfs.join(opts.get(b'name'))
3516 newpath = repo.vfs.join(opts.get(b'name'))
3515 else:
3517 else:
3516 newpath, i = lastsavename(q.path)
3518 newpath, i = lastsavename(q.path)
3517 if not newpath:
3519 if not newpath:
3518 ui.warn(_(b"no saved queues found, please use -n\n"))
3520 ui.warn(_(b"no saved queues found, please use -n\n"))
3519 return 1
3521 return 1
3520 mergeq = queue(ui, repo.baseui, repo.path, newpath)
3522 mergeq = queue(ui, repo.baseui, repo.path, newpath)
3521 ui.warn(_(b"merging with queue at: %s\n") % mergeq.path)
3523 ui.warn(_(b"merging with queue at: %s\n") % mergeq.path)
3522 ret = q.push(
3524 ret = q.push(
3523 repo,
3525 repo,
3524 patch,
3526 patch,
3525 force=opts.get(b'force'),
3527 force=opts.get(b'force'),
3526 list=opts.get(b'list'),
3528 list=opts.get(b'list'),
3527 mergeq=mergeq,
3529 mergeq=mergeq,
3528 all=opts.get(b'all'),
3530 all=opts.get(b'all'),
3529 move=opts.get(b'move'),
3531 move=opts.get(b'move'),
3530 exact=opts.get(b'exact'),
3532 exact=opts.get(b'exact'),
3531 nobackup=opts.get(b'no_backup'),
3533 nobackup=opts.get(b'no_backup'),
3532 keepchanges=opts.get(b'keep_changes'),
3534 keepchanges=opts.get(b'keep_changes'),
3533 )
3535 )
3534 return ret
3536 return ret
3535
3537
3536
3538
3537 @command(
3539 @command(
3538 b"qpop",
3540 b"qpop",
3539 [
3541 [
3540 (b'a', b'all', None, _(b'pop all patches')),
3542 (b'a', b'all', None, _(b'pop all patches')),
3541 (b'n', b'name', b'', _(b'queue name to pop (DEPRECATED)'), _(b'NAME')),
3543 (b'n', b'name', b'', _(b'queue name to pop (DEPRECATED)'), _(b'NAME')),
3542 (
3544 (
3543 b'',
3545 b'',
3544 b'keep-changes',
3546 b'keep-changes',
3545 None,
3547 None,
3546 _(b'tolerate non-conflicting local changes'),
3548 _(b'tolerate non-conflicting local changes'),
3547 ),
3549 ),
3548 (b'f', b'force', None, _(b'forget any local changes to patched files')),
3550 (b'f', b'force', None, _(b'forget any local changes to patched files')),
3549 (b'', b'no-backup', None, _(b'do not save backup copies of files')),
3551 (b'', b'no-backup', None, _(b'do not save backup copies of files')),
3550 ],
3552 ],
3551 _(b'hg qpop [-a] [-f] [PATCH | INDEX]'),
3553 _(b'hg qpop [-a] [-f] [PATCH | INDEX]'),
3552 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3554 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3553 helpbasic=True,
3555 helpbasic=True,
3554 )
3556 )
3555 def pop(ui, repo, patch=None, **opts):
3557 def pop(ui, repo, patch=None, **opts):
3556 """pop the current patch off the stack
3558 """pop the current patch off the stack
3557
3559
3558 Without argument, pops off the top of the patch stack. If given a
3560 Without argument, pops off the top of the patch stack. If given a
3559 patch name, keeps popping off patches until the named patch is at
3561 patch name, keeps popping off patches until the named patch is at
3560 the top of the stack.
3562 the top of the stack.
3561
3563
3562 By default, abort if the working directory contains uncommitted
3564 By default, abort if the working directory contains uncommitted
3563 changes. With --keep-changes, abort only if the uncommitted files
3565 changes. With --keep-changes, abort only if the uncommitted files
3564 overlap with patched files. With -f/--force, backup and discard
3566 overlap with patched files. With -f/--force, backup and discard
3565 changes made to such files.
3567 changes made to such files.
3566
3568
3567 Return 0 on success.
3569 Return 0 on success.
3568 """
3570 """
3569 opts = pycompat.byteskwargs(opts)
3571 opts = pycompat.byteskwargs(opts)
3570 opts = fixkeepchangesopts(ui, opts)
3572 opts = fixkeepchangesopts(ui, opts)
3571 localupdate = True
3573 localupdate = True
3572 if opts.get(b'name'):
3574 if opts.get(b'name'):
3573 q = queue(ui, repo.baseui, repo.path, repo.vfs.join(opts.get(b'name')))
3575 q = queue(ui, repo.baseui, repo.path, repo.vfs.join(opts.get(b'name')))
3574 ui.warn(_(b'using patch queue: %s\n') % q.path)
3576 ui.warn(_(b'using patch queue: %s\n') % q.path)
3575 localupdate = False
3577 localupdate = False
3576 else:
3578 else:
3577 q = repo.mq
3579 q = repo.mq
3578 ret = q.pop(
3580 ret = q.pop(
3579 repo,
3581 repo,
3580 patch,
3582 patch,
3581 force=opts.get(b'force'),
3583 force=opts.get(b'force'),
3582 update=localupdate,
3584 update=localupdate,
3583 all=opts.get(b'all'),
3585 all=opts.get(b'all'),
3584 nobackup=opts.get(b'no_backup'),
3586 nobackup=opts.get(b'no_backup'),
3585 keepchanges=opts.get(b'keep_changes'),
3587 keepchanges=opts.get(b'keep_changes'),
3586 )
3588 )
3587 q.savedirty()
3589 q.savedirty()
3588 return ret
3590 return ret
3589
3591
3590
3592
3591 @command(
3593 @command(
3592 b"qrename|qmv",
3594 b"qrename|qmv",
3593 [],
3595 [],
3594 _(b'hg qrename PATCH1 [PATCH2]'),
3596 _(b'hg qrename PATCH1 [PATCH2]'),
3595 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3597 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3596 )
3598 )
3597 def rename(ui, repo, patch, name=None, **opts):
3599 def rename(ui, repo, patch, name=None, **opts):
3598 """rename a patch
3600 """rename a patch
3599
3601
3600 With one argument, renames the current patch to PATCH1.
3602 With one argument, renames the current patch to PATCH1.
3601 With two arguments, renames PATCH1 to PATCH2.
3603 With two arguments, renames PATCH1 to PATCH2.
3602
3604
3603 Returns 0 on success."""
3605 Returns 0 on success."""
3604 q = repo.mq
3606 q = repo.mq
3605 if not name:
3607 if not name:
3606 name = patch
3608 name = patch
3607 patch = None
3609 patch = None
3608
3610
3609 if patch:
3611 if patch:
3610 patch = q.lookup(patch)
3612 patch = q.lookup(patch)
3611 else:
3613 else:
3612 if not q.applied:
3614 if not q.applied:
3613 ui.write(_(b'no patches applied\n'))
3615 ui.write(_(b'no patches applied\n'))
3614 return
3616 return
3615 patch = q.lookup(b'qtip')
3617 patch = q.lookup(b'qtip')
3616 absdest = q.join(name)
3618 absdest = q.join(name)
3617 if os.path.isdir(absdest):
3619 if os.path.isdir(absdest):
3618 name = normname(os.path.join(name, os.path.basename(patch)))
3620 name = normname(os.path.join(name, os.path.basename(patch)))
3619 absdest = q.join(name)
3621 absdest = q.join(name)
3620 q.checkpatchname(name)
3622 q.checkpatchname(name)
3621
3623
3622 ui.note(_(b'renaming %s to %s\n') % (patch, name))
3624 ui.note(_(b'renaming %s to %s\n') % (patch, name))
3623 i = q.findseries(patch)
3625 i = q.findseries(patch)
3624 guards = q.guard_re.findall(q.fullseries[i])
3626 guards = q.guard_re.findall(q.fullseries[i])
3625 q.fullseries[i] = name + b''.join([b' #' + g for g in guards])
3627 q.fullseries[i] = name + b''.join([b' #' + g for g in guards])
3626 q.parseseries()
3628 q.parseseries()
3627 q.seriesdirty = True
3629 q.seriesdirty = True
3628
3630
3629 info = q.isapplied(patch)
3631 info = q.isapplied(patch)
3630 if info:
3632 if info:
3631 q.applied[info[0]] = statusentry(info[1], name)
3633 q.applied[info[0]] = statusentry(info[1], name)
3632 q.applieddirty = True
3634 q.applieddirty = True
3633
3635
3634 destdir = os.path.dirname(absdest)
3636 destdir = os.path.dirname(absdest)
3635 if not os.path.isdir(destdir):
3637 if not os.path.isdir(destdir):
3636 os.makedirs(destdir)
3638 os.makedirs(destdir)
3637 util.rename(q.join(patch), absdest)
3639 util.rename(q.join(patch), absdest)
3638 r = q.qrepo()
3640 r = q.qrepo()
3639 if r and patch in r.dirstate:
3641 if r and patch in r.dirstate:
3640 wctx = r[None]
3642 wctx = r[None]
3641 with r.wlock():
3643 with r.wlock():
3642 if r.dirstate[patch] == b'a':
3644 if r.dirstate[patch] == b'a':
3643 r.dirstate.set_untracked(patch)
3645 r.dirstate.set_untracked(patch)
3644 r.dirstate.set_tracked(name)
3646 r.dirstate.set_tracked(name)
3645 else:
3647 else:
3646 wctx.copy(patch, name)
3648 wctx.copy(patch, name)
3647 wctx.forget([patch])
3649 wctx.forget([patch])
3648
3650
3649 q.savedirty()
3651 q.savedirty()
3650
3652
3651
3653
3652 @command(
3654 @command(
3653 b"qrestore",
3655 b"qrestore",
3654 [
3656 [
3655 (b'd', b'delete', None, _(b'delete save entry')),
3657 (b'd', b'delete', None, _(b'delete save entry')),
3656 (b'u', b'update', None, _(b'update queue working directory')),
3658 (b'u', b'update', None, _(b'update queue working directory')),
3657 ],
3659 ],
3658 _(b'hg qrestore [-d] [-u] REV'),
3660 _(b'hg qrestore [-d] [-u] REV'),
3659 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3661 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3660 )
3662 )
3661 def restore(ui, repo, rev, **opts):
3663 def restore(ui, repo, rev, **opts):
3662 """restore the queue state saved by a revision (DEPRECATED)
3664 """restore the queue state saved by a revision (DEPRECATED)
3663
3665
3664 This command is deprecated, use :hg:`rebase` instead."""
3666 This command is deprecated, use :hg:`rebase` instead."""
3665 rev = repo.lookup(rev)
3667 rev = repo.lookup(rev)
3666 q = repo.mq
3668 q = repo.mq
3667 q.restore(repo, rev, delete=opts.get('delete'), qupdate=opts.get('update'))
3669 q.restore(repo, rev, delete=opts.get('delete'), qupdate=opts.get('update'))
3668 q.savedirty()
3670 q.savedirty()
3669 return 0
3671 return 0
3670
3672
3671
3673
3672 @command(
3674 @command(
3673 b"qsave",
3675 b"qsave",
3674 [
3676 [
3675 (b'c', b'copy', None, _(b'copy patch directory')),
3677 (b'c', b'copy', None, _(b'copy patch directory')),
3676 (b'n', b'name', b'', _(b'copy directory name'), _(b'NAME')),
3678 (b'n', b'name', b'', _(b'copy directory name'), _(b'NAME')),
3677 (b'e', b'empty', None, _(b'clear queue status file')),
3679 (b'e', b'empty', None, _(b'clear queue status file')),
3678 (b'f', b'force', None, _(b'force copy')),
3680 (b'f', b'force', None, _(b'force copy')),
3679 ]
3681 ]
3680 + cmdutil.commitopts,
3682 + cmdutil.commitopts,
3681 _(b'hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'),
3683 _(b'hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'),
3682 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3684 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3683 )
3685 )
3684 def save(ui, repo, **opts):
3686 def save(ui, repo, **opts):
3685 """save current queue state (DEPRECATED)
3687 """save current queue state (DEPRECATED)
3686
3688
3687 This command is deprecated, use :hg:`rebase` instead."""
3689 This command is deprecated, use :hg:`rebase` instead."""
3688 q = repo.mq
3690 q = repo.mq
3689 opts = pycompat.byteskwargs(opts)
3691 opts = pycompat.byteskwargs(opts)
3690 message = cmdutil.logmessage(ui, opts)
3692 message = cmdutil.logmessage(ui, opts)
3691 ret = q.save(repo, msg=message)
3693 ret = q.save(repo, msg=message)
3692 if ret:
3694 if ret:
3693 return ret
3695 return ret
3694 q.savedirty() # save to .hg/patches before copying
3696 q.savedirty() # save to .hg/patches before copying
3695 if opts.get(b'copy'):
3697 if opts.get(b'copy'):
3696 path = q.path
3698 path = q.path
3697 if opts.get(b'name'):
3699 if opts.get(b'name'):
3698 newpath = os.path.join(q.basepath, opts.get(b'name'))
3700 newpath = os.path.join(q.basepath, opts.get(b'name'))
3699 if os.path.exists(newpath):
3701 if os.path.exists(newpath):
3700 if not os.path.isdir(newpath):
3702 if not os.path.isdir(newpath):
3701 raise error.Abort(
3703 raise error.Abort(
3702 _(b'destination %s exists and is not a directory')
3704 _(b'destination %s exists and is not a directory')
3703 % newpath
3705 % newpath
3704 )
3706 )
3705 if not opts.get(b'force'):
3707 if not opts.get(b'force'):
3706 raise error.Abort(
3708 raise error.Abort(
3707 _(b'destination %s exists, use -f to force') % newpath
3709 _(b'destination %s exists, use -f to force') % newpath
3708 )
3710 )
3709 else:
3711 else:
3710 newpath = savename(path)
3712 newpath = savename(path)
3711 ui.warn(_(b"copy %s to %s\n") % (path, newpath))
3713 ui.warn(_(b"copy %s to %s\n") % (path, newpath))
3712 util.copyfiles(path, newpath)
3714 util.copyfiles(path, newpath)
3713 if opts.get(b'empty'):
3715 if opts.get(b'empty'):
3714 del q.applied[:]
3716 del q.applied[:]
3715 q.applieddirty = True
3717 q.applieddirty = True
3716 q.savedirty()
3718 q.savedirty()
3717 return 0
3719 return 0
3718
3720
3719
3721
3720 @command(
3722 @command(
3721 b"qselect",
3723 b"qselect",
3722 [
3724 [
3723 (b'n', b'none', None, _(b'disable all guards')),
3725 (b'n', b'none', None, _(b'disable all guards')),
3724 (b's', b'series', None, _(b'list all guards in series file')),
3726 (b's', b'series', None, _(b'list all guards in series file')),
3725 (b'', b'pop', None, _(b'pop to before first guarded applied patch')),
3727 (b'', b'pop', None, _(b'pop to before first guarded applied patch')),
3726 (b'', b'reapply', None, _(b'pop, then reapply patches')),
3728 (b'', b'reapply', None, _(b'pop, then reapply patches')),
3727 ],
3729 ],
3728 _(b'hg qselect [OPTION]... [GUARD]...'),
3730 _(b'hg qselect [OPTION]... [GUARD]...'),
3729 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3731 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3730 )
3732 )
3731 def select(ui, repo, *args, **opts):
3733 def select(ui, repo, *args, **opts):
3732 """set or print guarded patches to push
3734 """set or print guarded patches to push
3733
3735
3734 Use the :hg:`qguard` command to set or print guards on patch, then use
3736 Use the :hg:`qguard` command to set or print guards on patch, then use
3735 qselect to tell mq which guards to use. A patch will be pushed if
3737 qselect to tell mq which guards to use. A patch will be pushed if
3736 it has no guards or any positive guards match the currently
3738 it has no guards or any positive guards match the currently
3737 selected guard, but will not be pushed if any negative guards
3739 selected guard, but will not be pushed if any negative guards
3738 match the current guard. For example::
3740 match the current guard. For example::
3739
3741
3740 qguard foo.patch -- -stable (negative guard)
3742 qguard foo.patch -- -stable (negative guard)
3741 qguard bar.patch +stable (positive guard)
3743 qguard bar.patch +stable (positive guard)
3742 qselect stable
3744 qselect stable
3743
3745
3744 This activates the "stable" guard. mq will skip foo.patch (because
3746 This activates the "stable" guard. mq will skip foo.patch (because
3745 it has a negative match) but push bar.patch (because it has a
3747 it has a negative match) but push bar.patch (because it has a
3746 positive match).
3748 positive match).
3747
3749
3748 With no arguments, prints the currently active guards.
3750 With no arguments, prints the currently active guards.
3749 With one argument, sets the active guard.
3751 With one argument, sets the active guard.
3750
3752
3751 Use -n/--none to deactivate guards (no other arguments needed).
3753 Use -n/--none to deactivate guards (no other arguments needed).
3752 When no guards are active, patches with positive guards are
3754 When no guards are active, patches with positive guards are
3753 skipped and patches with negative guards are pushed.
3755 skipped and patches with negative guards are pushed.
3754
3756
3755 qselect can change the guards on applied patches. It does not pop
3757 qselect can change the guards on applied patches. It does not pop
3756 guarded patches by default. Use --pop to pop back to the last
3758 guarded patches by default. Use --pop to pop back to the last
3757 applied patch that is not guarded. Use --reapply (which implies
3759 applied patch that is not guarded. Use --reapply (which implies
3758 --pop) to push back to the current patch afterwards, but skip
3760 --pop) to push back to the current patch afterwards, but skip
3759 guarded patches.
3761 guarded patches.
3760
3762
3761 Use -s/--series to print a list of all guards in the series file
3763 Use -s/--series to print a list of all guards in the series file
3762 (no other arguments needed). Use -v for more information.
3764 (no other arguments needed). Use -v for more information.
3763
3765
3764 Returns 0 on success."""
3766 Returns 0 on success."""
3765
3767
3766 q = repo.mq
3768 q = repo.mq
3767 opts = pycompat.byteskwargs(opts)
3769 opts = pycompat.byteskwargs(opts)
3768 guards = q.active()
3770 guards = q.active()
3769 pushable = lambda i: q.pushable(q.applied[i].name)[0]
3771 pushable = lambda i: q.pushable(q.applied[i].name)[0]
3770 if args or opts.get(b'none'):
3772 if args or opts.get(b'none'):
3771 old_unapplied = q.unapplied(repo)
3773 old_unapplied = q.unapplied(repo)
3772 old_guarded = [
3774 old_guarded = [
3773 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)
3774 ]
3776 ]
3775 q.setactive(args)
3777 q.setactive(args)
3776 q.savedirty()
3778 q.savedirty()
3777 if not args:
3779 if not args:
3778 ui.status(_(b'guards deactivated\n'))
3780 ui.status(_(b'guards deactivated\n'))
3779 if not opts.get(b'pop') and not opts.get(b'reapply'):
3781 if not opts.get(b'pop') and not opts.get(b'reapply'):
3780 unapplied = q.unapplied(repo)
3782 unapplied = q.unapplied(repo)
3781 guarded = [
3783 guarded = [
3782 i for i in pycompat.xrange(len(q.applied)) if not pushable(i)
3784 i for i in pycompat.xrange(len(q.applied)) if not pushable(i)
3783 ]
3785 ]
3784 if len(unapplied) != len(old_unapplied):
3786 if len(unapplied) != len(old_unapplied):
3785 ui.status(
3787 ui.status(
3786 _(
3788 _(
3787 b'number of unguarded, unapplied patches has '
3789 b'number of unguarded, unapplied patches has '
3788 b'changed from %d to %d\n'
3790 b'changed from %d to %d\n'
3789 )
3791 )
3790 % (len(old_unapplied), len(unapplied))
3792 % (len(old_unapplied), len(unapplied))
3791 )
3793 )
3792 if len(guarded) != len(old_guarded):
3794 if len(guarded) != len(old_guarded):
3793 ui.status(
3795 ui.status(
3794 _(
3796 _(
3795 b'number of guarded, applied patches has changed '
3797 b'number of guarded, applied patches has changed '
3796 b'from %d to %d\n'
3798 b'from %d to %d\n'
3797 )
3799 )
3798 % (len(old_guarded), len(guarded))
3800 % (len(old_guarded), len(guarded))
3799 )
3801 )
3800 elif opts.get(b'series'):
3802 elif opts.get(b'series'):
3801 guards = {}
3803 guards = {}
3802 noguards = 0
3804 noguards = 0
3803 for gs in q.seriesguards:
3805 for gs in q.seriesguards:
3804 if not gs:
3806 if not gs:
3805 noguards += 1
3807 noguards += 1
3806 for g in gs:
3808 for g in gs:
3807 guards.setdefault(g, 0)
3809 guards.setdefault(g, 0)
3808 guards[g] += 1
3810 guards[g] += 1
3809 if ui.verbose:
3811 if ui.verbose:
3810 guards[b'NONE'] = noguards
3812 guards[b'NONE'] = noguards
3811 guards = list(guards.items())
3813 guards = list(guards.items())
3812 guards.sort(key=lambda x: x[0][1:])
3814 guards.sort(key=lambda x: x[0][1:])
3813 if guards:
3815 if guards:
3814 ui.note(_(b'guards in series file:\n'))
3816 ui.note(_(b'guards in series file:\n'))
3815 for guard, count in guards:
3817 for guard, count in guards:
3816 ui.note(b'%2d ' % count)
3818 ui.note(b'%2d ' % count)
3817 ui.write(guard, b'\n')
3819 ui.write(guard, b'\n')
3818 else:
3820 else:
3819 ui.note(_(b'no guards in series file\n'))
3821 ui.note(_(b'no guards in series file\n'))
3820 else:
3822 else:
3821 if guards:
3823 if guards:
3822 ui.note(_(b'active guards:\n'))
3824 ui.note(_(b'active guards:\n'))
3823 for g in guards:
3825 for g in guards:
3824 ui.write(g, b'\n')
3826 ui.write(g, b'\n')
3825 else:
3827 else:
3826 ui.write(_(b'no active guards\n'))
3828 ui.write(_(b'no active guards\n'))
3827 reapply = opts.get(b'reapply') and q.applied and q.applied[-1].name
3829 reapply = opts.get(b'reapply') and q.applied and q.applied[-1].name
3828 popped = False
3830 popped = False
3829 if opts.get(b'pop') or opts.get(b'reapply'):
3831 if opts.get(b'pop') or opts.get(b'reapply'):
3830 for i in pycompat.xrange(len(q.applied)):
3832 for i in pycompat.xrange(len(q.applied)):
3831 if not pushable(i):
3833 if not pushable(i):
3832 ui.status(_(b'popping guarded patches\n'))
3834 ui.status(_(b'popping guarded patches\n'))
3833 popped = True
3835 popped = True
3834 if i == 0:
3836 if i == 0:
3835 q.pop(repo, all=True)
3837 q.pop(repo, all=True)
3836 else:
3838 else:
3837 q.pop(repo, q.applied[i - 1].name)
3839 q.pop(repo, q.applied[i - 1].name)
3838 break
3840 break
3839 if popped:
3841 if popped:
3840 try:
3842 try:
3841 if reapply:
3843 if reapply:
3842 ui.status(_(b'reapplying unguarded patches\n'))
3844 ui.status(_(b'reapplying unguarded patches\n'))
3843 q.push(repo, reapply)
3845 q.push(repo, reapply)
3844 finally:
3846 finally:
3845 q.savedirty()
3847 q.savedirty()
3846
3848
3847
3849
3848 @command(
3850 @command(
3849 b"qfinish",
3851 b"qfinish",
3850 [(b'a', b'applied', None, _(b'finish all applied changesets'))],
3852 [(b'a', b'applied', None, _(b'finish all applied changesets'))],
3851 _(b'hg qfinish [-a] [REV]...'),
3853 _(b'hg qfinish [-a] [REV]...'),
3852 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3854 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3853 )
3855 )
3854 def finish(ui, repo, *revrange, **opts):
3856 def finish(ui, repo, *revrange, **opts):
3855 """move applied patches into repository history
3857 """move applied patches into repository history
3856
3858
3857 Finishes the specified revisions (corresponding to applied
3859 Finishes the specified revisions (corresponding to applied
3858 patches) by moving them out of mq control into regular repository
3860 patches) by moving them out of mq control into regular repository
3859 history.
3861 history.
3860
3862
3861 Accepts a revision range or the -a/--applied option. If --applied
3863 Accepts a revision range or the -a/--applied option. If --applied
3862 is specified, all applied mq revisions are removed from mq
3864 is specified, all applied mq revisions are removed from mq
3863 control. Otherwise, the given revisions must be at the base of the
3865 control. Otherwise, the given revisions must be at the base of the
3864 stack of applied patches.
3866 stack of applied patches.
3865
3867
3866 This can be especially useful if your changes have been applied to
3868 This can be especially useful if your changes have been applied to
3867 an upstream repository, or if you are about to push your changes
3869 an upstream repository, or if you are about to push your changes
3868 to upstream.
3870 to upstream.
3869
3871
3870 Returns 0 on success.
3872 Returns 0 on success.
3871 """
3873 """
3872 if not opts.get('applied') and not revrange:
3874 if not opts.get('applied') and not revrange:
3873 raise error.Abort(_(b'no revisions specified'))
3875 raise error.Abort(_(b'no revisions specified'))
3874 elif opts.get('applied'):
3876 elif opts.get('applied'):
3875 revrange = (b'qbase::qtip',) + revrange
3877 revrange = (b'qbase::qtip',) + revrange
3876
3878
3877 q = repo.mq
3879 q = repo.mq
3878 if not q.applied:
3880 if not q.applied:
3879 ui.status(_(b'no patches applied\n'))
3881 ui.status(_(b'no patches applied\n'))
3880 return 0
3882 return 0
3881
3883
3882 revs = scmutil.revrange(repo, revrange)
3884 revs = scmutil.revrange(repo, revrange)
3883 if repo[b'.'].rev() in revs and repo[None].files():
3885 if repo[b'.'].rev() in revs and repo[None].files():
3884 ui.warn(_(b'warning: uncommitted changes in the working directory\n'))
3886 ui.warn(_(b'warning: uncommitted changes in the working directory\n'))
3885 # queue.finish may changes phases but leave the responsibility to lock the
3887 # queue.finish may changes phases but leave the responsibility to lock the
3886 # repo to the caller to avoid deadlock with wlock. This command code is
3888 # repo to the caller to avoid deadlock with wlock. This command code is
3887 # responsibility for this locking.
3889 # responsibility for this locking.
3888 with repo.lock():
3890 with repo.lock():
3889 q.finish(repo, revs)
3891 q.finish(repo, revs)
3890 q.savedirty()
3892 q.savedirty()
3891 return 0
3893 return 0
3892
3894
3893
3895
3894 @command(
3896 @command(
3895 b"qqueue",
3897 b"qqueue",
3896 [
3898 [
3897 (b'l', b'list', False, _(b'list all available queues')),
3899 (b'l', b'list', False, _(b'list all available queues')),
3898 (b'', b'active', False, _(b'print name of active queue')),
3900 (b'', b'active', False, _(b'print name of active queue')),
3899 (b'c', b'create', False, _(b'create new queue')),
3901 (b'c', b'create', False, _(b'create new queue')),
3900 (b'', b'rename', False, _(b'rename active queue')),
3902 (b'', b'rename', False, _(b'rename active queue')),
3901 (b'', b'delete', False, _(b'delete reference to queue')),
3903 (b'', b'delete', False, _(b'delete reference to queue')),
3902 (b'', b'purge', False, _(b'delete queue, and remove patch dir')),
3904 (b'', b'purge', False, _(b'delete queue, and remove patch dir')),
3903 ],
3905 ],
3904 _(b'[OPTION] [QUEUE]'),
3906 _(b'[OPTION] [QUEUE]'),
3905 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3907 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3906 )
3908 )
3907 def qqueue(ui, repo, name=None, **opts):
3909 def qqueue(ui, repo, name=None, **opts):
3908 """manage multiple patch queues
3910 """manage multiple patch queues
3909
3911
3910 Supports switching between different patch queues, as well as creating
3912 Supports switching between different patch queues, as well as creating
3911 new patch queues and deleting existing ones.
3913 new patch queues and deleting existing ones.
3912
3914
3913 Omitting a queue name or specifying -l/--list will show you the registered
3915 Omitting a queue name or specifying -l/--list will show you the registered
3914 queues - by default the "normal" patches queue is registered. The currently
3916 queues - by default the "normal" patches queue is registered. The currently
3915 active queue will be marked with "(active)". Specifying --active will print
3917 active queue will be marked with "(active)". Specifying --active will print
3916 only the name of the active queue.
3918 only the name of the active queue.
3917
3919
3918 To create a new queue, use -c/--create. The queue is automatically made
3920 To create a new queue, use -c/--create. The queue is automatically made
3919 active, except in the case where there are applied patches from the
3921 active, except in the case where there are applied patches from the
3920 currently active queue in the repository. Then the queue will only be
3922 currently active queue in the repository. Then the queue will only be
3921 created and switching will fail.
3923 created and switching will fail.
3922
3924
3923 To delete an existing queue, use --delete. You cannot delete the currently
3925 To delete an existing queue, use --delete. You cannot delete the currently
3924 active queue.
3926 active queue.
3925
3927
3926 Returns 0 on success.
3928 Returns 0 on success.
3927 """
3929 """
3928 q = repo.mq
3930 q = repo.mq
3929 _defaultqueue = b'patches'
3931 _defaultqueue = b'patches'
3930 _allqueues = b'patches.queues'
3932 _allqueues = b'patches.queues'
3931 _activequeue = b'patches.queue'
3933 _activequeue = b'patches.queue'
3932
3934
3933 def _getcurrent():
3935 def _getcurrent():
3934 cur = os.path.basename(q.path)
3936 cur = os.path.basename(q.path)
3935 if cur.startswith(b'patches-'):
3937 if cur.startswith(b'patches-'):
3936 cur = cur[8:]
3938 cur = cur[8:]
3937 return cur
3939 return cur
3938
3940
3939 def _noqueues():
3941 def _noqueues():
3940 try:
3942 try:
3941 fh = repo.vfs(_allqueues, b'r')
3943 fh = repo.vfs(_allqueues, b'r')
3942 fh.close()
3944 fh.close()
3943 except IOError:
3945 except IOError:
3944 return True
3946 return True
3945
3947
3946 return False
3948 return False
3947
3949
3948 def _getqueues():
3950 def _getqueues():
3949 current = _getcurrent()
3951 current = _getcurrent()
3950
3952
3951 try:
3953 try:
3952 fh = repo.vfs(_allqueues, b'r')
3954 fh = repo.vfs(_allqueues, b'r')
3953 queues = [queue.strip() for queue in fh if queue.strip()]
3955 queues = [queue.strip() for queue in fh if queue.strip()]
3954 fh.close()
3956 fh.close()
3955 if current not in queues:
3957 if current not in queues:
3956 queues.append(current)
3958 queues.append(current)
3957 except IOError:
3959 except IOError:
3958 queues = [_defaultqueue]
3960 queues = [_defaultqueue]
3959
3961
3960 return sorted(queues)
3962 return sorted(queues)
3961
3963
3962 def _setactive(name):
3964 def _setactive(name):
3963 if q.applied:
3965 if q.applied:
3964 raise error.Abort(
3966 raise error.Abort(
3965 _(
3967 _(
3966 b'new queue created, but cannot make active '
3968 b'new queue created, but cannot make active '
3967 b'as patches are applied'
3969 b'as patches are applied'
3968 )
3970 )
3969 )
3971 )
3970 _setactivenocheck(name)
3972 _setactivenocheck(name)
3971
3973
3972 def _setactivenocheck(name):
3974 def _setactivenocheck(name):
3973 fh = repo.vfs(_activequeue, b'w')
3975 fh = repo.vfs(_activequeue, b'w')
3974 if name != b'patches':
3976 if name != b'patches':
3975 fh.write(name)
3977 fh.write(name)
3976 fh.close()
3978 fh.close()
3977
3979
3978 def _addqueue(name):
3980 def _addqueue(name):
3979 fh = repo.vfs(_allqueues, b'a')
3981 fh = repo.vfs(_allqueues, b'a')
3980 fh.write(b'%s\n' % (name,))
3982 fh.write(b'%s\n' % (name,))
3981 fh.close()
3983 fh.close()
3982
3984
3983 def _queuedir(name):
3985 def _queuedir(name):
3984 if name == b'patches':
3986 if name == b'patches':
3985 return repo.vfs.join(b'patches')
3987 return repo.vfs.join(b'patches')
3986 else:
3988 else:
3987 return repo.vfs.join(b'patches-' + name)
3989 return repo.vfs.join(b'patches-' + name)
3988
3990
3989 def _validname(name):
3991 def _validname(name):
3990 for n in name:
3992 for n in name:
3991 if n in b':\\/.':
3993 if n in b':\\/.':
3992 return False
3994 return False
3993 return True
3995 return True
3994
3996
3995 def _delete(name):
3997 def _delete(name):
3996 if name not in existing:
3998 if name not in existing:
3997 raise error.Abort(_(b'cannot delete queue that does not exist'))
3999 raise error.Abort(_(b'cannot delete queue that does not exist'))
3998
4000
3999 current = _getcurrent()
4001 current = _getcurrent()
4000
4002
4001 if name == current:
4003 if name == current:
4002 raise error.Abort(_(b'cannot delete currently active queue'))
4004 raise error.Abort(_(b'cannot delete currently active queue'))
4003
4005
4004 fh = repo.vfs(b'patches.queues.new', b'w')
4006 fh = repo.vfs(b'patches.queues.new', b'w')
4005 for queue in existing:
4007 for queue in existing:
4006 if queue == name:
4008 if queue == name:
4007 continue
4009 continue
4008 fh.write(b'%s\n' % (queue,))
4010 fh.write(b'%s\n' % (queue,))
4009 fh.close()
4011 fh.close()
4010 repo.vfs.rename(b'patches.queues.new', _allqueues)
4012 repo.vfs.rename(b'patches.queues.new', _allqueues)
4011
4013
4012 opts = pycompat.byteskwargs(opts)
4014 opts = pycompat.byteskwargs(opts)
4013 if not name or opts.get(b'list') or opts.get(b'active'):
4015 if not name or opts.get(b'list') or opts.get(b'active'):
4014 current = _getcurrent()
4016 current = _getcurrent()
4015 if opts.get(b'active'):
4017 if opts.get(b'active'):
4016 ui.write(b'%s\n' % (current,))
4018 ui.write(b'%s\n' % (current,))
4017 return
4019 return
4018 for queue in _getqueues():
4020 for queue in _getqueues():
4019 ui.write(b'%s' % (queue,))
4021 ui.write(b'%s' % (queue,))
4020 if queue == current and not ui.quiet:
4022 if queue == current and not ui.quiet:
4021 ui.write(_(b' (active)\n'))
4023 ui.write(_(b' (active)\n'))
4022 else:
4024 else:
4023 ui.write(b'\n')
4025 ui.write(b'\n')
4024 return
4026 return
4025
4027
4026 if not _validname(name):
4028 if not _validname(name):
4027 raise error.Abort(
4029 raise error.Abort(
4028 _(b'invalid queue name, may not contain the characters ":\\/."')
4030 _(b'invalid queue name, may not contain the characters ":\\/."')
4029 )
4031 )
4030
4032
4031 with repo.wlock():
4033 with repo.wlock():
4032 existing = _getqueues()
4034 existing = _getqueues()
4033
4035
4034 if opts.get(b'create'):
4036 if opts.get(b'create'):
4035 if name in existing:
4037 if name in existing:
4036 raise error.Abort(_(b'queue "%s" already exists') % name)
4038 raise error.Abort(_(b'queue "%s" already exists') % name)
4037 if _noqueues():
4039 if _noqueues():
4038 _addqueue(_defaultqueue)
4040 _addqueue(_defaultqueue)
4039 _addqueue(name)
4041 _addqueue(name)
4040 _setactive(name)
4042 _setactive(name)
4041 elif opts.get(b'rename'):
4043 elif opts.get(b'rename'):
4042 current = _getcurrent()
4044 current = _getcurrent()
4043 if name == current:
4045 if name == current:
4044 raise error.Abort(
4046 raise error.Abort(
4045 _(b'can\'t rename "%s" to its current name') % name
4047 _(b'can\'t rename "%s" to its current name') % name
4046 )
4048 )
4047 if name in existing:
4049 if name in existing:
4048 raise error.Abort(_(b'queue "%s" already exists') % name)
4050 raise error.Abort(_(b'queue "%s" already exists') % name)
4049
4051
4050 olddir = _queuedir(current)
4052 olddir = _queuedir(current)
4051 newdir = _queuedir(name)
4053 newdir = _queuedir(name)
4052
4054
4053 if os.path.exists(newdir):
4055 if os.path.exists(newdir):
4054 raise error.Abort(
4056 raise error.Abort(
4055 _(b'non-queue directory "%s" already exists') % newdir
4057 _(b'non-queue directory "%s" already exists') % newdir
4056 )
4058 )
4057
4059
4058 fh = repo.vfs(b'patches.queues.new', b'w')
4060 fh = repo.vfs(b'patches.queues.new', b'w')
4059 for queue in existing:
4061 for queue in existing:
4060 if queue == current:
4062 if queue == current:
4061 fh.write(b'%s\n' % (name,))
4063 fh.write(b'%s\n' % (name,))
4062 if os.path.exists(olddir):
4064 if os.path.exists(olddir):
4063 util.rename(olddir, newdir)
4065 util.rename(olddir, newdir)
4064 else:
4066 else:
4065 fh.write(b'%s\n' % (queue,))
4067 fh.write(b'%s\n' % (queue,))
4066 fh.close()
4068 fh.close()
4067 repo.vfs.rename(b'patches.queues.new', _allqueues)
4069 repo.vfs.rename(b'patches.queues.new', _allqueues)
4068 _setactivenocheck(name)
4070 _setactivenocheck(name)
4069 elif opts.get(b'delete'):
4071 elif opts.get(b'delete'):
4070 _delete(name)
4072 _delete(name)
4071 elif opts.get(b'purge'):
4073 elif opts.get(b'purge'):
4072 if name in existing:
4074 if name in existing:
4073 _delete(name)
4075 _delete(name)
4074 qdir = _queuedir(name)
4076 qdir = _queuedir(name)
4075 if os.path.exists(qdir):
4077 if os.path.exists(qdir):
4076 shutil.rmtree(qdir)
4078 shutil.rmtree(qdir)
4077 else:
4079 else:
4078 if name not in existing:
4080 if name not in existing:
4079 raise error.Abort(_(b'use --create to create a new queue'))
4081 raise error.Abort(_(b'use --create to create a new queue'))
4080 _setactive(name)
4082 _setactive(name)
4081
4083
4082
4084
4083 def mqphasedefaults(repo, roots):
4085 def mqphasedefaults(repo, roots):
4084 """callback used to set mq changeset as secret when no phase data exists"""
4086 """callback used to set mq changeset as secret when no phase data exists"""
4085 if repo.mq.applied:
4087 if repo.mq.applied:
4086 if repo.ui.configbool(b'mq', b'secret'):
4088 if repo.ui.configbool(b'mq', b'secret'):
4087 mqphase = phases.secret
4089 mqphase = phases.secret
4088 else:
4090 else:
4089 mqphase = phases.draft
4091 mqphase = phases.draft
4090 qbase = repo[repo.mq.applied[0].node]
4092 qbase = repo[repo.mq.applied[0].node]
4091 roots[mqphase].add(qbase.node())
4093 roots[mqphase].add(qbase.node())
4092 return roots
4094 return roots
4093
4095
4094
4096
4095 def reposetup(ui, repo):
4097 def reposetup(ui, repo):
4096 class mqrepo(repo.__class__):
4098 class mqrepo(repo.__class__):
4097 @localrepo.unfilteredpropertycache
4099 @localrepo.unfilteredpropertycache
4098 def mq(self):
4100 def mq(self):
4099 return queue(self.ui, self.baseui, self.path)
4101 return queue(self.ui, self.baseui, self.path)
4100
4102
4101 def invalidateall(self):
4103 def invalidateall(self):
4102 super(mqrepo, self).invalidateall()
4104 super(mqrepo, self).invalidateall()
4103 if localrepo.hasunfilteredcache(self, 'mq'):
4105 if localrepo.hasunfilteredcache(self, 'mq'):
4104 # recreate mq in case queue path was changed
4106 # recreate mq in case queue path was changed
4105 delattr(self.unfiltered(), 'mq')
4107 delattr(self.unfiltered(), 'mq')
4106
4108
4107 def abortifwdirpatched(self, errmsg, force=False):
4109 def abortifwdirpatched(self, errmsg, force=False):
4108 if self.mq.applied and self.mq.checkapplied and not force:
4110 if self.mq.applied and self.mq.checkapplied and not force:
4109 parents = self.dirstate.parents()
4111 parents = self.dirstate.parents()
4110 patches = [s.node for s in self.mq.applied]
4112 patches = [s.node for s in self.mq.applied]
4111 if any(p in patches for p in parents):
4113 if any(p in patches for p in parents):
4112 raise error.Abort(errmsg)
4114 raise error.Abort(errmsg)
4113
4115
4114 def commit(
4116 def commit(
4115 self,
4117 self,
4116 text=b"",
4118 text=b"",
4117 user=None,
4119 user=None,
4118 date=None,
4120 date=None,
4119 match=None,
4121 match=None,
4120 force=False,
4122 force=False,
4121 editor=False,
4123 editor=False,
4122 extra=None,
4124 extra=None,
4123 ):
4125 ):
4124 if extra is None:
4126 if extra is None:
4125 extra = {}
4127 extra = {}
4126 self.abortifwdirpatched(
4128 self.abortifwdirpatched(
4127 _(b'cannot commit over an applied mq patch'), force
4129 _(b'cannot commit over an applied mq patch'), force
4128 )
4130 )
4129
4131
4130 return super(mqrepo, self).commit(
4132 return super(mqrepo, self).commit(
4131 text, user, date, match, force, editor, extra
4133 text, user, date, match, force, editor, extra
4132 )
4134 )
4133
4135
4134 def checkpush(self, pushop):
4136 def checkpush(self, pushop):
4135 if self.mq.applied and self.mq.checkapplied and not pushop.force:
4137 if self.mq.applied and self.mq.checkapplied and not pushop.force:
4136 outapplied = [e.node for e in self.mq.applied]
4138 outapplied = [e.node for e in self.mq.applied]
4137 if pushop.revs:
4139 if pushop.revs:
4138 # Assume applied patches have no non-patch descendants and
4140 # Assume applied patches have no non-patch descendants and
4139 # are not on remote already. Filtering any changeset not
4141 # are not on remote already. Filtering any changeset not
4140 # pushed.
4142 # pushed.
4141 heads = set(pushop.revs)
4143 heads = set(pushop.revs)
4142 for node in reversed(outapplied):
4144 for node in reversed(outapplied):
4143 if node in heads:
4145 if node in heads:
4144 break
4146 break
4145 else:
4147 else:
4146 outapplied.pop()
4148 outapplied.pop()
4147 # looking for pushed and shared changeset
4149 # looking for pushed and shared changeset
4148 for node in outapplied:
4150 for node in outapplied:
4149 if self[node].phase() < phases.secret:
4151 if self[node].phase() < phases.secret:
4150 raise error.Abort(_(b'source has mq patches applied'))
4152 raise error.Abort(_(b'source has mq patches applied'))
4151 # no non-secret patches pushed
4153 # no non-secret patches pushed
4152 super(mqrepo, self).checkpush(pushop)
4154 super(mqrepo, self).checkpush(pushop)
4153
4155
4154 def _findtags(self):
4156 def _findtags(self):
4155 '''augment tags from base class with patch tags'''
4157 '''augment tags from base class with patch tags'''
4156 result = super(mqrepo, self)._findtags()
4158 result = super(mqrepo, self)._findtags()
4157
4159
4158 q = self.mq
4160 q = self.mq
4159 if not q.applied:
4161 if not q.applied:
4160 return result
4162 return result
4161
4163
4162 mqtags = [(patch.node, patch.name) for patch in q.applied]
4164 mqtags = [(patch.node, patch.name) for patch in q.applied]
4163
4165
4164 try:
4166 try:
4165 # for now ignore filtering business
4167 # for now ignore filtering business
4166 self.unfiltered().changelog.rev(mqtags[-1][0])
4168 self.unfiltered().changelog.rev(mqtags[-1][0])
4167 except error.LookupError:
4169 except error.LookupError:
4168 self.ui.warn(
4170 self.ui.warn(
4169 _(b'mq status file refers to unknown node %s\n')
4171 _(b'mq status file refers to unknown node %s\n')
4170 % short(mqtags[-1][0])
4172 % short(mqtags[-1][0])
4171 )
4173 )
4172 return result
4174 return result
4173
4175
4174 # do not add fake tags for filtered revisions
4176 # do not add fake tags for filtered revisions
4175 included = self.changelog.hasnode
4177 included = self.changelog.hasnode
4176 mqtags = [mqt for mqt in mqtags if included(mqt[0])]
4178 mqtags = [mqt for mqt in mqtags if included(mqt[0])]
4177 if not mqtags:
4179 if not mqtags:
4178 return result
4180 return result
4179
4181
4180 mqtags.append((mqtags[-1][0], b'qtip'))
4182 mqtags.append((mqtags[-1][0], b'qtip'))
4181 mqtags.append((mqtags[0][0], b'qbase'))
4183 mqtags.append((mqtags[0][0], b'qbase'))
4182 mqtags.append((self.changelog.parents(mqtags[0][0])[0], b'qparent'))
4184 mqtags.append((self.changelog.parents(mqtags[0][0])[0], b'qparent'))
4183 tags = result[0]
4185 tags = result[0]
4184 for patch in mqtags:
4186 for patch in mqtags:
4185 if patch[1] in tags:
4187 if patch[1] in tags:
4186 self.ui.warn(
4188 self.ui.warn(
4187 _(b'tag %s overrides mq patch of the same name\n')
4189 _(b'tag %s overrides mq patch of the same name\n')
4188 % patch[1]
4190 % patch[1]
4189 )
4191 )
4190 else:
4192 else:
4191 tags[patch[1]] = patch[0]
4193 tags[patch[1]] = patch[0]
4192
4194
4193 return result
4195 return result
4194
4196
4195 if repo.local():
4197 if repo.local():
4196 repo.__class__ = mqrepo
4198 repo.__class__ = mqrepo
4197
4199
4198 repo._phasedefaults.append(mqphasedefaults)
4200 repo._phasedefaults.append(mqphasedefaults)
4199
4201
4200
4202
4201 def mqimport(orig, ui, repo, *args, **kwargs):
4203 def mqimport(orig, ui, repo, *args, **kwargs):
4202 if util.safehasattr(repo, b'abortifwdirpatched') and not kwargs.get(
4204 if util.safehasattr(repo, b'abortifwdirpatched') and not kwargs.get(
4203 'no_commit', False
4205 'no_commit', False
4204 ):
4206 ):
4205 repo.abortifwdirpatched(
4207 repo.abortifwdirpatched(
4206 _(b'cannot import over an applied patch'), kwargs.get('force')
4208 _(b'cannot import over an applied patch'), kwargs.get('force')
4207 )
4209 )
4208 return orig(ui, repo, *args, **kwargs)
4210 return orig(ui, repo, *args, **kwargs)
4209
4211
4210
4212
4211 def mqinit(orig, ui, *args, **kwargs):
4213 def mqinit(orig, ui, *args, **kwargs):
4212 mq = kwargs.pop('mq', None)
4214 mq = kwargs.pop('mq', None)
4213
4215
4214 if not mq:
4216 if not mq:
4215 return orig(ui, *args, **kwargs)
4217 return orig(ui, *args, **kwargs)
4216
4218
4217 if args:
4219 if args:
4218 repopath = args[0]
4220 repopath = args[0]
4219 if not hg.islocal(repopath):
4221 if not hg.islocal(repopath):
4220 raise error.Abort(
4222 raise error.Abort(
4221 _(b'only a local queue repository may be initialized')
4223 _(b'only a local queue repository may be initialized')
4222 )
4224 )
4223 else:
4225 else:
4224 repopath = cmdutil.findrepo(encoding.getcwd())
4226 repopath = cmdutil.findrepo(encoding.getcwd())
4225 if not repopath:
4227 if not repopath:
4226 raise error.Abort(
4228 raise error.Abort(
4227 _(b'there is no Mercurial repository here (.hg not found)')
4229 _(b'there is no Mercurial repository here (.hg not found)')
4228 )
4230 )
4229 repo = hg.repository(ui, repopath)
4231 repo = hg.repository(ui, repopath)
4230 return qinit(ui, repo, True)
4232 return qinit(ui, repo, True)
4231
4233
4232
4234
4233 def mqcommand(orig, ui, repo, *args, **kwargs):
4235 def mqcommand(orig, ui, repo, *args, **kwargs):
4234 """Add --mq option to operate on patch repository instead of main"""
4236 """Add --mq option to operate on patch repository instead of main"""
4235
4237
4236 # some commands do not like getting unknown options
4238 # some commands do not like getting unknown options
4237 mq = kwargs.pop('mq', None)
4239 mq = kwargs.pop('mq', None)
4238
4240
4239 if not mq:
4241 if not mq:
4240 return orig(ui, repo, *args, **kwargs)
4242 return orig(ui, repo, *args, **kwargs)
4241
4243
4242 q = repo.mq
4244 q = repo.mq
4243 r = q.qrepo()
4245 r = q.qrepo()
4244 if not r:
4246 if not r:
4245 raise error.Abort(_(b'no queue repository'))
4247 raise error.Abort(_(b'no queue repository'))
4246 return orig(r.ui, r, *args, **kwargs)
4248 return orig(r.ui, r, *args, **kwargs)
4247
4249
4248
4250
4249 def summaryhook(ui, repo):
4251 def summaryhook(ui, repo):
4250 q = repo.mq
4252 q = repo.mq
4251 m = []
4253 m = []
4252 a, u = len(q.applied), len(q.unapplied(repo))
4254 a, u = len(q.applied), len(q.unapplied(repo))
4253 if a:
4255 if a:
4254 m.append(ui.label(_(b"%d applied"), b'qseries.applied') % a)
4256 m.append(ui.label(_(b"%d applied"), b'qseries.applied') % a)
4255 if u:
4257 if u:
4256 m.append(ui.label(_(b"%d unapplied"), b'qseries.unapplied') % u)
4258 m.append(ui.label(_(b"%d unapplied"), b'qseries.unapplied') % u)
4257 if m:
4259 if m:
4258 # i18n: column positioning for "hg summary"
4260 # i18n: column positioning for "hg summary"
4259 ui.write(_(b"mq: %s\n") % b', '.join(m))
4261 ui.write(_(b"mq: %s\n") % b', '.join(m))
4260 else:
4262 else:
4261 # i18n: column positioning for "hg summary"
4263 # i18n: column positioning for "hg summary"
4262 ui.note(_(b"mq: (empty queue)\n"))
4264 ui.note(_(b"mq: (empty queue)\n"))
4263
4265
4264
4266
4265 revsetpredicate = registrar.revsetpredicate()
4267 revsetpredicate = registrar.revsetpredicate()
4266
4268
4267
4269
4268 @revsetpredicate(b'mq()')
4270 @revsetpredicate(b'mq()')
4269 def revsetmq(repo, subset, x):
4271 def revsetmq(repo, subset, x):
4270 """Changesets managed by MQ."""
4272 """Changesets managed by MQ."""
4271 revsetlang.getargs(x, 0, 0, _(b"mq takes no arguments"))
4273 revsetlang.getargs(x, 0, 0, _(b"mq takes no arguments"))
4272 applied = {repo[r.node].rev() for r in repo.mq.applied}
4274 applied = {repo[r.node].rev() for r in repo.mq.applied}
4273 return smartset.baseset([r for r in subset if r in applied])
4275 return smartset.baseset([r for r in subset if r in applied])
4274
4276
4275
4277
4276 # tell hggettext to extract docstrings from these functions:
4278 # tell hggettext to extract docstrings from these functions:
4277 i18nfunctions = [revsetmq]
4279 i18nfunctions = [revsetmq]
4278
4280
4279
4281
4280 def extsetup(ui):
4282 def extsetup(ui):
4281 # Ensure mq wrappers are called first, regardless of extension load order by
4283 # Ensure mq wrappers are called first, regardless of extension load order by
4282 # NOT wrapping in uisetup() and instead deferring to init stage two here.
4284 # NOT wrapping in uisetup() and instead deferring to init stage two here.
4283 mqopt = [(b'', b'mq', None, _(b"operate on patch repository"))]
4285 mqopt = [(b'', b'mq', None, _(b"operate on patch repository"))]
4284
4286
4285 extensions.wrapcommand(commands.table, b'import', mqimport)
4287 extensions.wrapcommand(commands.table, b'import', mqimport)
4286 cmdutil.summaryhooks.add(b'mq', summaryhook)
4288 cmdutil.summaryhooks.add(b'mq', summaryhook)
4287
4289
4288 entry = extensions.wrapcommand(commands.table, b'init', mqinit)
4290 entry = extensions.wrapcommand(commands.table, b'init', mqinit)
4289 entry[1].extend(mqopt)
4291 entry[1].extend(mqopt)
4290
4292
4291 def dotable(cmdtable):
4293 def dotable(cmdtable):
4292 for cmd, entry in pycompat.iteritems(cmdtable):
4294 for cmd, entry in pycompat.iteritems(cmdtable):
4293 cmd = cmdutil.parsealiases(cmd)[0]
4295 cmd = cmdutil.parsealiases(cmd)[0]
4294 func = entry[0]
4296 func = entry[0]
4295 if func.norepo:
4297 if func.norepo:
4296 continue
4298 continue
4297 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
4299 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
4298 entry[1].extend(mqopt)
4300 entry[1].extend(mqopt)
4299
4301
4300 dotable(commands.table)
4302 dotable(commands.table)
4301
4303
4302 thismodule = sys.modules["hgext.mq"]
4304 thismodule = sys.modules["hgext.mq"]
4303 for extname, extmodule in extensions.extensions():
4305 for extname, extmodule in extensions.extensions():
4304 if extmodule != thismodule:
4306 if extmodule != thismodule:
4305 dotable(getattr(extmodule, 'cmdtable', {}))
4307 dotable(getattr(extmodule, 'cmdtable', {}))
4306
4308
4307
4309
4308 colortable = {
4310 colortable = {
4309 b'qguard.negative': b'red',
4311 b'qguard.negative': b'red',
4310 b'qguard.positive': b'yellow',
4312 b'qguard.positive': b'yellow',
4311 b'qguard.unguarded': b'green',
4313 b'qguard.unguarded': b'green',
4312 b'qseries.applied': b'blue bold underline',
4314 b'qseries.applied': b'blue bold underline',
4313 b'qseries.guarded': b'black bold',
4315 b'qseries.guarded': b'black bold',
4314 b'qseries.missing': b'red bold',
4316 b'qseries.missing': b'red bold',
4315 b'qseries.unapplied': b'black bold',
4317 b'qseries.unapplied': b'black bold',
4316 }
4318 }
General Comments 0
You need to be logged in to leave comments. Login now