##// END OF EJS Templates
mq/qqueue: print current queue name...
"Yann E. MORIN" -
r14987:3709cca3 default
parent child Browse files
Show More
@@ -1,3287 +1,3292 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 behaviour can be configured with::
31 files creations or deletions. This behaviour 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 You will by default be managing a patch queue named "patches". You can
41 You will by default be managing a patch queue named "patches". You can
42 create other, independent patch queues with the :hg:`qqueue` command.
42 create other, independent patch queues with the :hg:`qqueue` command.
43 '''
43 '''
44
44
45 from mercurial.i18n import _
45 from mercurial.i18n import _
46 from mercurial.node import bin, hex, short, nullid, nullrev
46 from mercurial.node import bin, hex, short, nullid, nullrev
47 from mercurial.lock import release
47 from mercurial.lock import release
48 from mercurial import commands, cmdutil, hg, scmutil, util, revset
48 from mercurial import commands, cmdutil, hg, scmutil, util, revset
49 from mercurial import repair, extensions, url, error
49 from mercurial import repair, extensions, url, error
50 from mercurial import patch as patchmod
50 from mercurial import patch as patchmod
51 import os, re, errno, shutil
51 import os, re, errno, shutil
52
52
53 commands.norepo += " qclone"
53 commands.norepo += " qclone"
54
54
55 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
55 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
56
56
57 cmdtable = {}
57 cmdtable = {}
58 command = cmdutil.command(cmdtable)
58 command = cmdutil.command(cmdtable)
59
59
60 # Patch names looks like unix-file names.
60 # Patch names looks like unix-file names.
61 # They must be joinable with queue directory and result in the patch path.
61 # They must be joinable with queue directory and result in the patch path.
62 normname = util.normpath
62 normname = util.normpath
63
63
64 class statusentry(object):
64 class statusentry(object):
65 def __init__(self, node, name):
65 def __init__(self, node, name):
66 self.node, self.name = node, name
66 self.node, self.name = node, name
67 def __repr__(self):
67 def __repr__(self):
68 return hex(self.node) + ':' + self.name
68 return hex(self.node) + ':' + self.name
69
69
70 class patchheader(object):
70 class patchheader(object):
71 def __init__(self, pf, plainmode=False):
71 def __init__(self, pf, plainmode=False):
72 def eatdiff(lines):
72 def eatdiff(lines):
73 while lines:
73 while lines:
74 l = lines[-1]
74 l = lines[-1]
75 if (l.startswith("diff -") or
75 if (l.startswith("diff -") or
76 l.startswith("Index:") or
76 l.startswith("Index:") or
77 l.startswith("===========")):
77 l.startswith("===========")):
78 del lines[-1]
78 del lines[-1]
79 else:
79 else:
80 break
80 break
81 def eatempty(lines):
81 def eatempty(lines):
82 while lines:
82 while lines:
83 if not lines[-1].strip():
83 if not lines[-1].strip():
84 del lines[-1]
84 del lines[-1]
85 else:
85 else:
86 break
86 break
87
87
88 message = []
88 message = []
89 comments = []
89 comments = []
90 user = None
90 user = None
91 date = None
91 date = None
92 parent = None
92 parent = None
93 format = None
93 format = None
94 subject = None
94 subject = None
95 branch = None
95 branch = None
96 nodeid = None
96 nodeid = None
97 diffstart = 0
97 diffstart = 0
98
98
99 for line in file(pf):
99 for line in file(pf):
100 line = line.rstrip()
100 line = line.rstrip()
101 if (line.startswith('diff --git')
101 if (line.startswith('diff --git')
102 or (diffstart and line.startswith('+++ '))):
102 or (diffstart and line.startswith('+++ '))):
103 diffstart = 2
103 diffstart = 2
104 break
104 break
105 diffstart = 0 # reset
105 diffstart = 0 # reset
106 if line.startswith("--- "):
106 if line.startswith("--- "):
107 diffstart = 1
107 diffstart = 1
108 continue
108 continue
109 elif format == "hgpatch":
109 elif format == "hgpatch":
110 # parse values when importing the result of an hg export
110 # parse values when importing the result of an hg export
111 if line.startswith("# User "):
111 if line.startswith("# User "):
112 user = line[7:]
112 user = line[7:]
113 elif line.startswith("# Date "):
113 elif line.startswith("# Date "):
114 date = line[7:]
114 date = line[7:]
115 elif line.startswith("# Parent "):
115 elif line.startswith("# Parent "):
116 parent = line[9:].lstrip()
116 parent = line[9:].lstrip()
117 elif line.startswith("# Branch "):
117 elif line.startswith("# Branch "):
118 branch = line[9:]
118 branch = line[9:]
119 elif line.startswith("# Node ID "):
119 elif line.startswith("# Node ID "):
120 nodeid = line[10:]
120 nodeid = line[10:]
121 elif not line.startswith("# ") and line:
121 elif not line.startswith("# ") and line:
122 message.append(line)
122 message.append(line)
123 format = None
123 format = None
124 elif line == '# HG changeset patch':
124 elif line == '# HG changeset patch':
125 message = []
125 message = []
126 format = "hgpatch"
126 format = "hgpatch"
127 elif (format != "tagdone" and (line.startswith("Subject: ") or
127 elif (format != "tagdone" and (line.startswith("Subject: ") or
128 line.startswith("subject: "))):
128 line.startswith("subject: "))):
129 subject = line[9:]
129 subject = line[9:]
130 format = "tag"
130 format = "tag"
131 elif (format != "tagdone" and (line.startswith("From: ") or
131 elif (format != "tagdone" and (line.startswith("From: ") or
132 line.startswith("from: "))):
132 line.startswith("from: "))):
133 user = line[6:]
133 user = line[6:]
134 format = "tag"
134 format = "tag"
135 elif (format != "tagdone" and (line.startswith("Date: ") or
135 elif (format != "tagdone" and (line.startswith("Date: ") or
136 line.startswith("date: "))):
136 line.startswith("date: "))):
137 date = line[6:]
137 date = line[6:]
138 format = "tag"
138 format = "tag"
139 elif format == "tag" and line == "":
139 elif format == "tag" and line == "":
140 # when looking for tags (subject: from: etc) they
140 # when looking for tags (subject: from: etc) they
141 # end once you find a blank line in the source
141 # end once you find a blank line in the source
142 format = "tagdone"
142 format = "tagdone"
143 elif message or line:
143 elif message or line:
144 message.append(line)
144 message.append(line)
145 comments.append(line)
145 comments.append(line)
146
146
147 eatdiff(message)
147 eatdiff(message)
148 eatdiff(comments)
148 eatdiff(comments)
149 # Remember the exact starting line of the patch diffs before consuming
149 # Remember the exact starting line of the patch diffs before consuming
150 # empty lines, for external use by TortoiseHg and others
150 # empty lines, for external use by TortoiseHg and others
151 self.diffstartline = len(comments)
151 self.diffstartline = len(comments)
152 eatempty(message)
152 eatempty(message)
153 eatempty(comments)
153 eatempty(comments)
154
154
155 # make sure message isn't empty
155 # make sure message isn't empty
156 if format and format.startswith("tag") and subject:
156 if format and format.startswith("tag") and subject:
157 message.insert(0, "")
157 message.insert(0, "")
158 message.insert(0, subject)
158 message.insert(0, subject)
159
159
160 self.message = message
160 self.message = message
161 self.comments = comments
161 self.comments = comments
162 self.user = user
162 self.user = user
163 self.date = date
163 self.date = date
164 self.parent = parent
164 self.parent = parent
165 # nodeid and branch are for external use by TortoiseHg and others
165 # nodeid and branch are for external use by TortoiseHg and others
166 self.nodeid = nodeid
166 self.nodeid = nodeid
167 self.branch = branch
167 self.branch = branch
168 self.haspatch = diffstart > 1
168 self.haspatch = diffstart > 1
169 self.plainmode = plainmode
169 self.plainmode = plainmode
170
170
171 def setuser(self, user):
171 def setuser(self, user):
172 if not self.updateheader(['From: ', '# User '], user):
172 if not self.updateheader(['From: ', '# User '], user):
173 try:
173 try:
174 patchheaderat = self.comments.index('# HG changeset patch')
174 patchheaderat = self.comments.index('# HG changeset patch')
175 self.comments.insert(patchheaderat + 1, '# User ' + user)
175 self.comments.insert(patchheaderat + 1, '# User ' + user)
176 except ValueError:
176 except ValueError:
177 if self.plainmode or self._hasheader(['Date: ']):
177 if self.plainmode or self._hasheader(['Date: ']):
178 self.comments = ['From: ' + user] + self.comments
178 self.comments = ['From: ' + user] + self.comments
179 else:
179 else:
180 tmp = ['# HG changeset patch', '# User ' + user, '']
180 tmp = ['# HG changeset patch', '# User ' + user, '']
181 self.comments = tmp + self.comments
181 self.comments = tmp + self.comments
182 self.user = user
182 self.user = user
183
183
184 def setdate(self, date):
184 def setdate(self, date):
185 if not self.updateheader(['Date: ', '# Date '], date):
185 if not self.updateheader(['Date: ', '# Date '], date):
186 try:
186 try:
187 patchheaderat = self.comments.index('# HG changeset patch')
187 patchheaderat = self.comments.index('# HG changeset patch')
188 self.comments.insert(patchheaderat + 1, '# Date ' + date)
188 self.comments.insert(patchheaderat + 1, '# Date ' + date)
189 except ValueError:
189 except ValueError:
190 if self.plainmode or self._hasheader(['From: ']):
190 if self.plainmode or self._hasheader(['From: ']):
191 self.comments = ['Date: ' + date] + self.comments
191 self.comments = ['Date: ' + date] + self.comments
192 else:
192 else:
193 tmp = ['# HG changeset patch', '# Date ' + date, '']
193 tmp = ['# HG changeset patch', '# Date ' + date, '']
194 self.comments = tmp + self.comments
194 self.comments = tmp + self.comments
195 self.date = date
195 self.date = date
196
196
197 def setparent(self, parent):
197 def setparent(self, parent):
198 if not self.updateheader(['# Parent '], parent):
198 if not self.updateheader(['# Parent '], parent):
199 try:
199 try:
200 patchheaderat = self.comments.index('# HG changeset patch')
200 patchheaderat = self.comments.index('# HG changeset patch')
201 self.comments.insert(patchheaderat + 1, '# Parent ' + parent)
201 self.comments.insert(patchheaderat + 1, '# Parent ' + parent)
202 except ValueError:
202 except ValueError:
203 pass
203 pass
204 self.parent = parent
204 self.parent = parent
205
205
206 def setmessage(self, message):
206 def setmessage(self, message):
207 if self.comments:
207 if self.comments:
208 self._delmsg()
208 self._delmsg()
209 self.message = [message]
209 self.message = [message]
210 self.comments += self.message
210 self.comments += self.message
211
211
212 def updateheader(self, prefixes, new):
212 def updateheader(self, prefixes, new):
213 '''Update all references to a field in the patch header.
213 '''Update all references to a field in the patch header.
214 Return whether the field is present.'''
214 Return whether the field is present.'''
215 res = False
215 res = False
216 for prefix in prefixes:
216 for prefix in prefixes:
217 for i in xrange(len(self.comments)):
217 for i in xrange(len(self.comments)):
218 if self.comments[i].startswith(prefix):
218 if self.comments[i].startswith(prefix):
219 self.comments[i] = prefix + new
219 self.comments[i] = prefix + new
220 res = True
220 res = True
221 break
221 break
222 return res
222 return res
223
223
224 def _hasheader(self, prefixes):
224 def _hasheader(self, prefixes):
225 '''Check if a header starts with any of the given prefixes.'''
225 '''Check if a header starts with any of the given prefixes.'''
226 for prefix in prefixes:
226 for prefix in prefixes:
227 for comment in self.comments:
227 for comment in self.comments:
228 if comment.startswith(prefix):
228 if comment.startswith(prefix):
229 return True
229 return True
230 return False
230 return False
231
231
232 def __str__(self):
232 def __str__(self):
233 if not self.comments:
233 if not self.comments:
234 return ''
234 return ''
235 return '\n'.join(self.comments) + '\n\n'
235 return '\n'.join(self.comments) + '\n\n'
236
236
237 def _delmsg(self):
237 def _delmsg(self):
238 '''Remove existing message, keeping the rest of the comments fields.
238 '''Remove existing message, keeping the rest of the comments fields.
239 If comments contains 'subject: ', message will prepend
239 If comments contains 'subject: ', message will prepend
240 the field and a blank line.'''
240 the field and a blank line.'''
241 if self.message:
241 if self.message:
242 subj = 'subject: ' + self.message[0].lower()
242 subj = 'subject: ' + self.message[0].lower()
243 for i in xrange(len(self.comments)):
243 for i in xrange(len(self.comments)):
244 if subj == self.comments[i].lower():
244 if subj == self.comments[i].lower():
245 del self.comments[i]
245 del self.comments[i]
246 self.message = self.message[2:]
246 self.message = self.message[2:]
247 break
247 break
248 ci = 0
248 ci = 0
249 for mi in self.message:
249 for mi in self.message:
250 while mi != self.comments[ci]:
250 while mi != self.comments[ci]:
251 ci += 1
251 ci += 1
252 del self.comments[ci]
252 del self.comments[ci]
253
253
254 class queue(object):
254 class queue(object):
255 def __init__(self, ui, path, patchdir=None):
255 def __init__(self, ui, path, patchdir=None):
256 self.basepath = path
256 self.basepath = path
257 try:
257 try:
258 fh = open(os.path.join(path, 'patches.queue'))
258 fh = open(os.path.join(path, 'patches.queue'))
259 cur = fh.read().rstrip()
259 cur = fh.read().rstrip()
260 fh.close()
260 fh.close()
261 if not cur:
261 if not cur:
262 curpath = os.path.join(path, 'patches')
262 curpath = os.path.join(path, 'patches')
263 else:
263 else:
264 curpath = os.path.join(path, 'patches-' + cur)
264 curpath = os.path.join(path, 'patches-' + cur)
265 except IOError:
265 except IOError:
266 curpath = os.path.join(path, 'patches')
266 curpath = os.path.join(path, 'patches')
267 self.path = patchdir or curpath
267 self.path = patchdir or curpath
268 self.opener = scmutil.opener(self.path)
268 self.opener = scmutil.opener(self.path)
269 self.ui = ui
269 self.ui = ui
270 self.applieddirty = 0
270 self.applieddirty = 0
271 self.seriesdirty = 0
271 self.seriesdirty = 0
272 self.added = []
272 self.added = []
273 self.seriespath = "series"
273 self.seriespath = "series"
274 self.statuspath = "status"
274 self.statuspath = "status"
275 self.guardspath = "guards"
275 self.guardspath = "guards"
276 self.activeguards = None
276 self.activeguards = None
277 self.guardsdirty = False
277 self.guardsdirty = False
278 # Handle mq.git as a bool with extended values
278 # Handle mq.git as a bool with extended values
279 try:
279 try:
280 gitmode = ui.configbool('mq', 'git', None)
280 gitmode = ui.configbool('mq', 'git', None)
281 if gitmode is None:
281 if gitmode is None:
282 raise error.ConfigError()
282 raise error.ConfigError()
283 self.gitmode = gitmode and 'yes' or 'no'
283 self.gitmode = gitmode and 'yes' or 'no'
284 except error.ConfigError:
284 except error.ConfigError:
285 self.gitmode = ui.config('mq', 'git', 'auto').lower()
285 self.gitmode = ui.config('mq', 'git', 'auto').lower()
286 self.plainmode = ui.configbool('mq', 'plain', False)
286 self.plainmode = ui.configbool('mq', 'plain', False)
287
287
288 @util.propertycache
288 @util.propertycache
289 def applied(self):
289 def applied(self):
290 if os.path.exists(self.join(self.statuspath)):
290 if os.path.exists(self.join(self.statuspath)):
291 def parselines(lines):
291 def parselines(lines):
292 for l in lines:
292 for l in lines:
293 entry = l.split(':', 1)
293 entry = l.split(':', 1)
294 if len(entry) > 1:
294 if len(entry) > 1:
295 n, name = entry
295 n, name = entry
296 yield statusentry(bin(n), name)
296 yield statusentry(bin(n), name)
297 elif l.strip():
297 elif l.strip():
298 self.ui.warn(_('malformated mq status line: %s\n') % entry)
298 self.ui.warn(_('malformated mq status line: %s\n') % entry)
299 # else we ignore empty lines
299 # else we ignore empty lines
300 lines = self.opener.read(self.statuspath).splitlines()
300 lines = self.opener.read(self.statuspath).splitlines()
301 return list(parselines(lines))
301 return list(parselines(lines))
302 return []
302 return []
303
303
304 @util.propertycache
304 @util.propertycache
305 def fullseries(self):
305 def fullseries(self):
306 if os.path.exists(self.join(self.seriespath)):
306 if os.path.exists(self.join(self.seriespath)):
307 return self.opener.read(self.seriespath).splitlines()
307 return self.opener.read(self.seriespath).splitlines()
308 return []
308 return []
309
309
310 @util.propertycache
310 @util.propertycache
311 def series(self):
311 def series(self):
312 self.parseseries()
312 self.parseseries()
313 return self.series
313 return self.series
314
314
315 @util.propertycache
315 @util.propertycache
316 def seriesguards(self):
316 def seriesguards(self):
317 self.parseseries()
317 self.parseseries()
318 return self.seriesguards
318 return self.seriesguards
319
319
320 def invalidate(self):
320 def invalidate(self):
321 for a in 'applied fullseries series seriesguards'.split():
321 for a in 'applied fullseries series seriesguards'.split():
322 if a in self.__dict__:
322 if a in self.__dict__:
323 delattr(self, a)
323 delattr(self, a)
324 self.applieddirty = 0
324 self.applieddirty = 0
325 self.seriesdirty = 0
325 self.seriesdirty = 0
326 self.guardsdirty = False
326 self.guardsdirty = False
327 self.activeguards = None
327 self.activeguards = None
328
328
329 def diffopts(self, opts={}, patchfn=None):
329 def diffopts(self, opts={}, patchfn=None):
330 diffopts = patchmod.diffopts(self.ui, opts)
330 diffopts = patchmod.diffopts(self.ui, opts)
331 if self.gitmode == 'auto':
331 if self.gitmode == 'auto':
332 diffopts.upgrade = True
332 diffopts.upgrade = True
333 elif self.gitmode == 'keep':
333 elif self.gitmode == 'keep':
334 pass
334 pass
335 elif self.gitmode in ('yes', 'no'):
335 elif self.gitmode in ('yes', 'no'):
336 diffopts.git = self.gitmode == 'yes'
336 diffopts.git = self.gitmode == 'yes'
337 else:
337 else:
338 raise util.Abort(_('mq.git option can be auto/keep/yes/no'
338 raise util.Abort(_('mq.git option can be auto/keep/yes/no'
339 ' got %s') % self.gitmode)
339 ' got %s') % self.gitmode)
340 if patchfn:
340 if patchfn:
341 diffopts = self.patchopts(diffopts, patchfn)
341 diffopts = self.patchopts(diffopts, patchfn)
342 return diffopts
342 return diffopts
343
343
344 def patchopts(self, diffopts, *patches):
344 def patchopts(self, diffopts, *patches):
345 """Return a copy of input diff options with git set to true if
345 """Return a copy of input diff options with git set to true if
346 referenced patch is a git patch and should be preserved as such.
346 referenced patch is a git patch and should be preserved as such.
347 """
347 """
348 diffopts = diffopts.copy()
348 diffopts = diffopts.copy()
349 if not diffopts.git and self.gitmode == 'keep':
349 if not diffopts.git and self.gitmode == 'keep':
350 for patchfn in patches:
350 for patchfn in patches:
351 patchf = self.opener(patchfn, 'r')
351 patchf = self.opener(patchfn, 'r')
352 # if the patch was a git patch, refresh it as a git patch
352 # if the patch was a git patch, refresh it as a git patch
353 for line in patchf:
353 for line in patchf:
354 if line.startswith('diff --git'):
354 if line.startswith('diff --git'):
355 diffopts.git = True
355 diffopts.git = True
356 break
356 break
357 patchf.close()
357 patchf.close()
358 return diffopts
358 return diffopts
359
359
360 def join(self, *p):
360 def join(self, *p):
361 return os.path.join(self.path, *p)
361 return os.path.join(self.path, *p)
362
362
363 def findseries(self, patch):
363 def findseries(self, patch):
364 def matchpatch(l):
364 def matchpatch(l):
365 l = l.split('#', 1)[0]
365 l = l.split('#', 1)[0]
366 return l.strip() == patch
366 return l.strip() == patch
367 for index, l in enumerate(self.fullseries):
367 for index, l in enumerate(self.fullseries):
368 if matchpatch(l):
368 if matchpatch(l):
369 return index
369 return index
370 return None
370 return None
371
371
372 guard_re = re.compile(r'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
372 guard_re = re.compile(r'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
373
373
374 def parseseries(self):
374 def parseseries(self):
375 self.series = []
375 self.series = []
376 self.seriesguards = []
376 self.seriesguards = []
377 for l in self.fullseries:
377 for l in self.fullseries:
378 h = l.find('#')
378 h = l.find('#')
379 if h == -1:
379 if h == -1:
380 patch = l
380 patch = l
381 comment = ''
381 comment = ''
382 elif h == 0:
382 elif h == 0:
383 continue
383 continue
384 else:
384 else:
385 patch = l[:h]
385 patch = l[:h]
386 comment = l[h:]
386 comment = l[h:]
387 patch = patch.strip()
387 patch = patch.strip()
388 if patch:
388 if patch:
389 if patch in self.series:
389 if patch in self.series:
390 raise util.Abort(_('%s appears more than once in %s') %
390 raise util.Abort(_('%s appears more than once in %s') %
391 (patch, self.join(self.seriespath)))
391 (patch, self.join(self.seriespath)))
392 self.series.append(patch)
392 self.series.append(patch)
393 self.seriesguards.append(self.guard_re.findall(comment))
393 self.seriesguards.append(self.guard_re.findall(comment))
394
394
395 def checkguard(self, guard):
395 def checkguard(self, guard):
396 if not guard:
396 if not guard:
397 return _('guard cannot be an empty string')
397 return _('guard cannot be an empty string')
398 bad_chars = '# \t\r\n\f'
398 bad_chars = '# \t\r\n\f'
399 first = guard[0]
399 first = guard[0]
400 if first in '-+':
400 if first in '-+':
401 return (_('guard %r starts with invalid character: %r') %
401 return (_('guard %r starts with invalid character: %r') %
402 (guard, first))
402 (guard, first))
403 for c in bad_chars:
403 for c in bad_chars:
404 if c in guard:
404 if c in guard:
405 return _('invalid character in guard %r: %r') % (guard, c)
405 return _('invalid character in guard %r: %r') % (guard, c)
406
406
407 def setactive(self, guards):
407 def setactive(self, guards):
408 for guard in guards:
408 for guard in guards:
409 bad = self.checkguard(guard)
409 bad = self.checkguard(guard)
410 if bad:
410 if bad:
411 raise util.Abort(bad)
411 raise util.Abort(bad)
412 guards = sorted(set(guards))
412 guards = sorted(set(guards))
413 self.ui.debug('active guards: %s\n' % ' '.join(guards))
413 self.ui.debug('active guards: %s\n' % ' '.join(guards))
414 self.activeguards = guards
414 self.activeguards = guards
415 self.guardsdirty = True
415 self.guardsdirty = True
416
416
417 def active(self):
417 def active(self):
418 if self.activeguards is None:
418 if self.activeguards is None:
419 self.activeguards = []
419 self.activeguards = []
420 try:
420 try:
421 guards = self.opener.read(self.guardspath).split()
421 guards = self.opener.read(self.guardspath).split()
422 except IOError, err:
422 except IOError, err:
423 if err.errno != errno.ENOENT:
423 if err.errno != errno.ENOENT:
424 raise
424 raise
425 guards = []
425 guards = []
426 for i, guard in enumerate(guards):
426 for i, guard in enumerate(guards):
427 bad = self.checkguard(guard)
427 bad = self.checkguard(guard)
428 if bad:
428 if bad:
429 self.ui.warn('%s:%d: %s\n' %
429 self.ui.warn('%s:%d: %s\n' %
430 (self.join(self.guardspath), i + 1, bad))
430 (self.join(self.guardspath), i + 1, bad))
431 else:
431 else:
432 self.activeguards.append(guard)
432 self.activeguards.append(guard)
433 return self.activeguards
433 return self.activeguards
434
434
435 def setguards(self, idx, guards):
435 def setguards(self, idx, guards):
436 for g in guards:
436 for g in guards:
437 if len(g) < 2:
437 if len(g) < 2:
438 raise util.Abort(_('guard %r too short') % g)
438 raise util.Abort(_('guard %r too short') % g)
439 if g[0] not in '-+':
439 if g[0] not in '-+':
440 raise util.Abort(_('guard %r starts with invalid char') % g)
440 raise util.Abort(_('guard %r starts with invalid char') % g)
441 bad = self.checkguard(g[1:])
441 bad = self.checkguard(g[1:])
442 if bad:
442 if bad:
443 raise util.Abort(bad)
443 raise util.Abort(bad)
444 drop = self.guard_re.sub('', self.fullseries[idx])
444 drop = self.guard_re.sub('', self.fullseries[idx])
445 self.fullseries[idx] = drop + ''.join([' #' + g for g in guards])
445 self.fullseries[idx] = drop + ''.join([' #' + g for g in guards])
446 self.parseseries()
446 self.parseseries()
447 self.seriesdirty = True
447 self.seriesdirty = True
448
448
449 def pushable(self, idx):
449 def pushable(self, idx):
450 if isinstance(idx, str):
450 if isinstance(idx, str):
451 idx = self.series.index(idx)
451 idx = self.series.index(idx)
452 patchguards = self.seriesguards[idx]
452 patchguards = self.seriesguards[idx]
453 if not patchguards:
453 if not patchguards:
454 return True, None
454 return True, None
455 guards = self.active()
455 guards = self.active()
456 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
456 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
457 if exactneg:
457 if exactneg:
458 return False, repr(exactneg[0])
458 return False, repr(exactneg[0])
459 pos = [g for g in patchguards if g[0] == '+']
459 pos = [g for g in patchguards if g[0] == '+']
460 exactpos = [g for g in pos if g[1:] in guards]
460 exactpos = [g for g in pos if g[1:] in guards]
461 if pos:
461 if pos:
462 if exactpos:
462 if exactpos:
463 return True, repr(exactpos[0])
463 return True, repr(exactpos[0])
464 return False, ' '.join(map(repr, pos))
464 return False, ' '.join(map(repr, pos))
465 return True, ''
465 return True, ''
466
466
467 def explainpushable(self, idx, all_patches=False):
467 def explainpushable(self, idx, all_patches=False):
468 write = all_patches and self.ui.write or self.ui.warn
468 write = all_patches and self.ui.write or self.ui.warn
469 if all_patches or self.ui.verbose:
469 if all_patches or self.ui.verbose:
470 if isinstance(idx, str):
470 if isinstance(idx, str):
471 idx = self.series.index(idx)
471 idx = self.series.index(idx)
472 pushable, why = self.pushable(idx)
472 pushable, why = self.pushable(idx)
473 if all_patches and pushable:
473 if all_patches and pushable:
474 if why is None:
474 if why is None:
475 write(_('allowing %s - no guards in effect\n') %
475 write(_('allowing %s - no guards in effect\n') %
476 self.series[idx])
476 self.series[idx])
477 else:
477 else:
478 if not why:
478 if not why:
479 write(_('allowing %s - no matching negative guards\n') %
479 write(_('allowing %s - no matching negative guards\n') %
480 self.series[idx])
480 self.series[idx])
481 else:
481 else:
482 write(_('allowing %s - guarded by %s\n') %
482 write(_('allowing %s - guarded by %s\n') %
483 (self.series[idx], why))
483 (self.series[idx], why))
484 if not pushable:
484 if not pushable:
485 if why:
485 if why:
486 write(_('skipping %s - guarded by %s\n') %
486 write(_('skipping %s - guarded by %s\n') %
487 (self.series[idx], why))
487 (self.series[idx], why))
488 else:
488 else:
489 write(_('skipping %s - no matching guards\n') %
489 write(_('skipping %s - no matching guards\n') %
490 self.series[idx])
490 self.series[idx])
491
491
492 def savedirty(self):
492 def savedirty(self):
493 def writelist(items, path):
493 def writelist(items, path):
494 fp = self.opener(path, 'w')
494 fp = self.opener(path, 'w')
495 for i in items:
495 for i in items:
496 fp.write("%s\n" % i)
496 fp.write("%s\n" % i)
497 fp.close()
497 fp.close()
498 if self.applieddirty:
498 if self.applieddirty:
499 writelist(map(str, self.applied), self.statuspath)
499 writelist(map(str, self.applied), self.statuspath)
500 if self.seriesdirty:
500 if self.seriesdirty:
501 writelist(self.fullseries, self.seriespath)
501 writelist(self.fullseries, self.seriespath)
502 if self.guardsdirty:
502 if self.guardsdirty:
503 writelist(self.activeguards, self.guardspath)
503 writelist(self.activeguards, self.guardspath)
504 if self.added:
504 if self.added:
505 qrepo = self.qrepo()
505 qrepo = self.qrepo()
506 if qrepo:
506 if qrepo:
507 qrepo[None].add(f for f in self.added if f not in qrepo[None])
507 qrepo[None].add(f for f in self.added if f not in qrepo[None])
508 self.added = []
508 self.added = []
509
509
510 def removeundo(self, repo):
510 def removeundo(self, repo):
511 undo = repo.sjoin('undo')
511 undo = repo.sjoin('undo')
512 if not os.path.exists(undo):
512 if not os.path.exists(undo):
513 return
513 return
514 try:
514 try:
515 os.unlink(undo)
515 os.unlink(undo)
516 except OSError, inst:
516 except OSError, inst:
517 self.ui.warn(_('error removing undo: %s\n') % str(inst))
517 self.ui.warn(_('error removing undo: %s\n') % str(inst))
518
518
519 def printdiff(self, repo, diffopts, node1, node2=None, files=None,
519 def printdiff(self, repo, diffopts, node1, node2=None, files=None,
520 fp=None, changes=None, opts={}):
520 fp=None, changes=None, opts={}):
521 stat = opts.get('stat')
521 stat = opts.get('stat')
522 m = scmutil.match(repo[node1], files, opts)
522 m = scmutil.match(repo[node1], files, opts)
523 cmdutil.diffordiffstat(self.ui, repo, diffopts, node1, node2, m,
523 cmdutil.diffordiffstat(self.ui, repo, diffopts, node1, node2, m,
524 changes, stat, fp)
524 changes, stat, fp)
525
525
526 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
526 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
527 # first try just applying the patch
527 # first try just applying the patch
528 (err, n) = self.apply(repo, [patch], update_status=False,
528 (err, n) = self.apply(repo, [patch], update_status=False,
529 strict=True, merge=rev)
529 strict=True, merge=rev)
530
530
531 if err == 0:
531 if err == 0:
532 return (err, n)
532 return (err, n)
533
533
534 if n is None:
534 if n is None:
535 raise util.Abort(_("apply failed for patch %s") % patch)
535 raise util.Abort(_("apply failed for patch %s") % patch)
536
536
537 self.ui.warn(_("patch didn't work out, merging %s\n") % patch)
537 self.ui.warn(_("patch didn't work out, merging %s\n") % patch)
538
538
539 # apply failed, strip away that rev and merge.
539 # apply failed, strip away that rev and merge.
540 hg.clean(repo, head)
540 hg.clean(repo, head)
541 self.strip(repo, [n], update=False, backup='strip')
541 self.strip(repo, [n], update=False, backup='strip')
542
542
543 ctx = repo[rev]
543 ctx = repo[rev]
544 ret = hg.merge(repo, rev)
544 ret = hg.merge(repo, rev)
545 if ret:
545 if ret:
546 raise util.Abort(_("update returned %d") % ret)
546 raise util.Abort(_("update returned %d") % ret)
547 n = repo.commit(ctx.description(), ctx.user(), force=True)
547 n = repo.commit(ctx.description(), ctx.user(), force=True)
548 if n is None:
548 if n is None:
549 raise util.Abort(_("repo commit failed"))
549 raise util.Abort(_("repo commit failed"))
550 try:
550 try:
551 ph = patchheader(mergeq.join(patch), self.plainmode)
551 ph = patchheader(mergeq.join(patch), self.plainmode)
552 except:
552 except:
553 raise util.Abort(_("unable to read %s") % patch)
553 raise util.Abort(_("unable to read %s") % patch)
554
554
555 diffopts = self.patchopts(diffopts, patch)
555 diffopts = self.patchopts(diffopts, patch)
556 patchf = self.opener(patch, "w")
556 patchf = self.opener(patch, "w")
557 comments = str(ph)
557 comments = str(ph)
558 if comments:
558 if comments:
559 patchf.write(comments)
559 patchf.write(comments)
560 self.printdiff(repo, diffopts, head, n, fp=patchf)
560 self.printdiff(repo, diffopts, head, n, fp=patchf)
561 patchf.close()
561 patchf.close()
562 self.removeundo(repo)
562 self.removeundo(repo)
563 return (0, n)
563 return (0, n)
564
564
565 def qparents(self, repo, rev=None):
565 def qparents(self, repo, rev=None):
566 if rev is None:
566 if rev is None:
567 (p1, p2) = repo.dirstate.parents()
567 (p1, p2) = repo.dirstate.parents()
568 if p2 == nullid:
568 if p2 == nullid:
569 return p1
569 return p1
570 if not self.applied:
570 if not self.applied:
571 return None
571 return None
572 return self.applied[-1].node
572 return self.applied[-1].node
573 p1, p2 = repo.changelog.parents(rev)
573 p1, p2 = repo.changelog.parents(rev)
574 if p2 != nullid and p2 in [x.node for x in self.applied]:
574 if p2 != nullid and p2 in [x.node for x in self.applied]:
575 return p2
575 return p2
576 return p1
576 return p1
577
577
578 def mergepatch(self, repo, mergeq, series, diffopts):
578 def mergepatch(self, repo, mergeq, series, diffopts):
579 if not self.applied:
579 if not self.applied:
580 # each of the patches merged in will have two parents. This
580 # each of the patches merged in will have two parents. This
581 # can confuse the qrefresh, qdiff, and strip code because it
581 # can confuse the qrefresh, qdiff, and strip code because it
582 # needs to know which parent is actually in the patch queue.
582 # needs to know which parent is actually in the patch queue.
583 # so, we insert a merge marker with only one parent. This way
583 # so, we insert a merge marker with only one parent. This way
584 # the first patch in the queue is never a merge patch
584 # the first patch in the queue is never a merge patch
585 #
585 #
586 pname = ".hg.patches.merge.marker"
586 pname = ".hg.patches.merge.marker"
587 n = repo.commit('[mq]: merge marker', force=True)
587 n = repo.commit('[mq]: merge marker', force=True)
588 self.removeundo(repo)
588 self.removeundo(repo)
589 self.applied.append(statusentry(n, pname))
589 self.applied.append(statusentry(n, pname))
590 self.applieddirty = 1
590 self.applieddirty = 1
591
591
592 head = self.qparents(repo)
592 head = self.qparents(repo)
593
593
594 for patch in series:
594 for patch in series:
595 patch = mergeq.lookup(patch, strict=True)
595 patch = mergeq.lookup(patch, strict=True)
596 if not patch:
596 if not patch:
597 self.ui.warn(_("patch %s does not exist\n") % patch)
597 self.ui.warn(_("patch %s does not exist\n") % patch)
598 return (1, None)
598 return (1, None)
599 pushable, reason = self.pushable(patch)
599 pushable, reason = self.pushable(patch)
600 if not pushable:
600 if not pushable:
601 self.explainpushable(patch, all_patches=True)
601 self.explainpushable(patch, all_patches=True)
602 continue
602 continue
603 info = mergeq.isapplied(patch)
603 info = mergeq.isapplied(patch)
604 if not info:
604 if not info:
605 self.ui.warn(_("patch %s is not applied\n") % patch)
605 self.ui.warn(_("patch %s is not applied\n") % patch)
606 return (1, None)
606 return (1, None)
607 rev = info[1]
607 rev = info[1]
608 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
608 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
609 if head:
609 if head:
610 self.applied.append(statusentry(head, patch))
610 self.applied.append(statusentry(head, patch))
611 self.applieddirty = 1
611 self.applieddirty = 1
612 if err:
612 if err:
613 return (err, head)
613 return (err, head)
614 self.savedirty()
614 self.savedirty()
615 return (0, head)
615 return (0, head)
616
616
617 def patch(self, repo, patchfile):
617 def patch(self, repo, patchfile):
618 '''Apply patchfile to the working directory.
618 '''Apply patchfile to the working directory.
619 patchfile: name of patch file'''
619 patchfile: name of patch file'''
620 files = set()
620 files = set()
621 try:
621 try:
622 fuzz = patchmod.patch(self.ui, repo, patchfile, strip=1,
622 fuzz = patchmod.patch(self.ui, repo, patchfile, strip=1,
623 files=files, eolmode=None)
623 files=files, eolmode=None)
624 return (True, list(files), fuzz)
624 return (True, list(files), fuzz)
625 except Exception, inst:
625 except Exception, inst:
626 self.ui.note(str(inst) + '\n')
626 self.ui.note(str(inst) + '\n')
627 if not self.ui.verbose:
627 if not self.ui.verbose:
628 self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
628 self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
629 return (False, list(files), False)
629 return (False, list(files), False)
630
630
631 def apply(self, repo, series, list=False, update_status=True,
631 def apply(self, repo, series, list=False, update_status=True,
632 strict=False, patchdir=None, merge=None, all_files=None):
632 strict=False, patchdir=None, merge=None, all_files=None):
633 wlock = lock = tr = None
633 wlock = lock = tr = None
634 try:
634 try:
635 wlock = repo.wlock()
635 wlock = repo.wlock()
636 lock = repo.lock()
636 lock = repo.lock()
637 tr = repo.transaction("qpush")
637 tr = repo.transaction("qpush")
638 try:
638 try:
639 ret = self._apply(repo, series, list, update_status,
639 ret = self._apply(repo, series, list, update_status,
640 strict, patchdir, merge, all_files=all_files)
640 strict, patchdir, merge, all_files=all_files)
641 tr.close()
641 tr.close()
642 self.savedirty()
642 self.savedirty()
643 return ret
643 return ret
644 except:
644 except:
645 try:
645 try:
646 tr.abort()
646 tr.abort()
647 finally:
647 finally:
648 repo.invalidate()
648 repo.invalidate()
649 repo.dirstate.invalidate()
649 repo.dirstate.invalidate()
650 raise
650 raise
651 finally:
651 finally:
652 release(tr, lock, wlock)
652 release(tr, lock, wlock)
653 self.removeundo(repo)
653 self.removeundo(repo)
654
654
655 def _apply(self, repo, series, list=False, update_status=True,
655 def _apply(self, repo, series, list=False, update_status=True,
656 strict=False, patchdir=None, merge=None, all_files=None):
656 strict=False, patchdir=None, merge=None, all_files=None):
657 '''returns (error, hash)
657 '''returns (error, hash)
658 error = 1 for unable to read, 2 for patch failed, 3 for patch fuzz'''
658 error = 1 for unable to read, 2 for patch failed, 3 for patch fuzz'''
659 # TODO unify with commands.py
659 # TODO unify with commands.py
660 if not patchdir:
660 if not patchdir:
661 patchdir = self.path
661 patchdir = self.path
662 err = 0
662 err = 0
663 n = None
663 n = None
664 for patchname in series:
664 for patchname in series:
665 pushable, reason = self.pushable(patchname)
665 pushable, reason = self.pushable(patchname)
666 if not pushable:
666 if not pushable:
667 self.explainpushable(patchname, all_patches=True)
667 self.explainpushable(patchname, all_patches=True)
668 continue
668 continue
669 self.ui.status(_("applying %s\n") % patchname)
669 self.ui.status(_("applying %s\n") % patchname)
670 pf = os.path.join(patchdir, patchname)
670 pf = os.path.join(patchdir, patchname)
671
671
672 try:
672 try:
673 ph = patchheader(self.join(patchname), self.plainmode)
673 ph = patchheader(self.join(patchname), self.plainmode)
674 except IOError:
674 except IOError:
675 self.ui.warn(_("unable to read %s\n") % patchname)
675 self.ui.warn(_("unable to read %s\n") % patchname)
676 err = 1
676 err = 1
677 break
677 break
678
678
679 message = ph.message
679 message = ph.message
680 if not message:
680 if not message:
681 # The commit message should not be translated
681 # The commit message should not be translated
682 message = "imported patch %s\n" % patchname
682 message = "imported patch %s\n" % patchname
683 else:
683 else:
684 if list:
684 if list:
685 # The commit message should not be translated
685 # The commit message should not be translated
686 message.append("\nimported patch %s" % patchname)
686 message.append("\nimported patch %s" % patchname)
687 message = '\n'.join(message)
687 message = '\n'.join(message)
688
688
689 if ph.haspatch:
689 if ph.haspatch:
690 (patcherr, files, fuzz) = self.patch(repo, pf)
690 (patcherr, files, fuzz) = self.patch(repo, pf)
691 if all_files is not None:
691 if all_files is not None:
692 all_files.update(files)
692 all_files.update(files)
693 patcherr = not patcherr
693 patcherr = not patcherr
694 else:
694 else:
695 self.ui.warn(_("patch %s is empty\n") % patchname)
695 self.ui.warn(_("patch %s is empty\n") % patchname)
696 patcherr, files, fuzz = 0, [], 0
696 patcherr, files, fuzz = 0, [], 0
697
697
698 if merge and files:
698 if merge and files:
699 # Mark as removed/merged and update dirstate parent info
699 # Mark as removed/merged and update dirstate parent info
700 removed = []
700 removed = []
701 merged = []
701 merged = []
702 for f in files:
702 for f in files:
703 if os.path.lexists(repo.wjoin(f)):
703 if os.path.lexists(repo.wjoin(f)):
704 merged.append(f)
704 merged.append(f)
705 else:
705 else:
706 removed.append(f)
706 removed.append(f)
707 for f in removed:
707 for f in removed:
708 repo.dirstate.remove(f)
708 repo.dirstate.remove(f)
709 for f in merged:
709 for f in merged:
710 repo.dirstate.merge(f)
710 repo.dirstate.merge(f)
711 p1, p2 = repo.dirstate.parents()
711 p1, p2 = repo.dirstate.parents()
712 repo.dirstate.setparents(p1, merge)
712 repo.dirstate.setparents(p1, merge)
713
713
714 match = scmutil.matchfiles(repo, files or [])
714 match = scmutil.matchfiles(repo, files or [])
715 n = repo.commit(message, ph.user, ph.date, match=match, force=True)
715 n = repo.commit(message, ph.user, ph.date, match=match, force=True)
716
716
717 if n is None:
717 if n is None:
718 raise util.Abort(_("repository commit failed"))
718 raise util.Abort(_("repository commit failed"))
719
719
720 if update_status:
720 if update_status:
721 self.applied.append(statusentry(n, patchname))
721 self.applied.append(statusentry(n, patchname))
722
722
723 if patcherr:
723 if patcherr:
724 self.ui.warn(_("patch failed, rejects left in working dir\n"))
724 self.ui.warn(_("patch failed, rejects left in working dir\n"))
725 err = 2
725 err = 2
726 break
726 break
727
727
728 if fuzz and strict:
728 if fuzz and strict:
729 self.ui.warn(_("fuzz found when applying patch, stopping\n"))
729 self.ui.warn(_("fuzz found when applying patch, stopping\n"))
730 err = 3
730 err = 3
731 break
731 break
732 return (err, n)
732 return (err, n)
733
733
734 def _cleanup(self, patches, numrevs, keep=False):
734 def _cleanup(self, patches, numrevs, keep=False):
735 if not keep:
735 if not keep:
736 r = self.qrepo()
736 r = self.qrepo()
737 if r:
737 if r:
738 r[None].forget(patches)
738 r[None].forget(patches)
739 for p in patches:
739 for p in patches:
740 os.unlink(self.join(p))
740 os.unlink(self.join(p))
741
741
742 if numrevs:
742 if numrevs:
743 qfinished = self.applied[:numrevs]
743 qfinished = self.applied[:numrevs]
744 del self.applied[:numrevs]
744 del self.applied[:numrevs]
745 self.applieddirty = 1
745 self.applieddirty = 1
746
746
747 unknown = []
747 unknown = []
748
748
749 for (i, p) in sorted([(self.findseries(p), p) for p in patches],
749 for (i, p) in sorted([(self.findseries(p), p) for p in patches],
750 reverse=True):
750 reverse=True):
751 if i is not None:
751 if i is not None:
752 del self.fullseries[i]
752 del self.fullseries[i]
753 else:
753 else:
754 unknown.append(p)
754 unknown.append(p)
755
755
756 if unknown:
756 if unknown:
757 if numrevs:
757 if numrevs:
758 rev = dict((entry.name, entry.node) for entry in qfinished)
758 rev = dict((entry.name, entry.node) for entry in qfinished)
759 for p in unknown:
759 for p in unknown:
760 msg = _('revision %s refers to unknown patches: %s\n')
760 msg = _('revision %s refers to unknown patches: %s\n')
761 self.ui.warn(msg % (short(rev[p]), p))
761 self.ui.warn(msg % (short(rev[p]), p))
762 else:
762 else:
763 msg = _('unknown patches: %s\n')
763 msg = _('unknown patches: %s\n')
764 raise util.Abort(''.join(msg % p for p in unknown))
764 raise util.Abort(''.join(msg % p for p in unknown))
765
765
766 self.parseseries()
766 self.parseseries()
767 self.seriesdirty = 1
767 self.seriesdirty = 1
768
768
769 def _revpatches(self, repo, revs):
769 def _revpatches(self, repo, revs):
770 firstrev = repo[self.applied[0].node].rev()
770 firstrev = repo[self.applied[0].node].rev()
771 patches = []
771 patches = []
772 for i, rev in enumerate(revs):
772 for i, rev in enumerate(revs):
773
773
774 if rev < firstrev:
774 if rev < firstrev:
775 raise util.Abort(_('revision %d is not managed') % rev)
775 raise util.Abort(_('revision %d is not managed') % rev)
776
776
777 ctx = repo[rev]
777 ctx = repo[rev]
778 base = self.applied[i].node
778 base = self.applied[i].node
779 if ctx.node() != base:
779 if ctx.node() != base:
780 msg = _('cannot delete revision %d above applied patches')
780 msg = _('cannot delete revision %d above applied patches')
781 raise util.Abort(msg % rev)
781 raise util.Abort(msg % rev)
782
782
783 patch = self.applied[i].name
783 patch = self.applied[i].name
784 for fmt in ('[mq]: %s', 'imported patch %s'):
784 for fmt in ('[mq]: %s', 'imported patch %s'):
785 if ctx.description() == fmt % patch:
785 if ctx.description() == fmt % patch:
786 msg = _('patch %s finalized without changeset message\n')
786 msg = _('patch %s finalized without changeset message\n')
787 repo.ui.status(msg % patch)
787 repo.ui.status(msg % patch)
788 break
788 break
789
789
790 patches.append(patch)
790 patches.append(patch)
791 return patches
791 return patches
792
792
793 def finish(self, repo, revs):
793 def finish(self, repo, revs):
794 patches = self._revpatches(repo, sorted(revs))
794 patches = self._revpatches(repo, sorted(revs))
795 self._cleanup(patches, len(patches))
795 self._cleanup(patches, len(patches))
796
796
797 def delete(self, repo, patches, opts):
797 def delete(self, repo, patches, opts):
798 if not patches and not opts.get('rev'):
798 if not patches and not opts.get('rev'):
799 raise util.Abort(_('qdelete requires at least one revision or '
799 raise util.Abort(_('qdelete requires at least one revision or '
800 'patch name'))
800 'patch name'))
801
801
802 realpatches = []
802 realpatches = []
803 for patch in patches:
803 for patch in patches:
804 patch = self.lookup(patch, strict=True)
804 patch = self.lookup(patch, strict=True)
805 info = self.isapplied(patch)
805 info = self.isapplied(patch)
806 if info:
806 if info:
807 raise util.Abort(_("cannot delete applied patch %s") % patch)
807 raise util.Abort(_("cannot delete applied patch %s") % patch)
808 if patch not in self.series:
808 if patch not in self.series:
809 raise util.Abort(_("patch %s not in series file") % patch)
809 raise util.Abort(_("patch %s not in series file") % patch)
810 if patch not in realpatches:
810 if patch not in realpatches:
811 realpatches.append(patch)
811 realpatches.append(patch)
812
812
813 numrevs = 0
813 numrevs = 0
814 if opts.get('rev'):
814 if opts.get('rev'):
815 if not self.applied:
815 if not self.applied:
816 raise util.Abort(_('no patches applied'))
816 raise util.Abort(_('no patches applied'))
817 revs = scmutil.revrange(repo, opts.get('rev'))
817 revs = scmutil.revrange(repo, opts.get('rev'))
818 if len(revs) > 1 and revs[0] > revs[1]:
818 if len(revs) > 1 and revs[0] > revs[1]:
819 revs.reverse()
819 revs.reverse()
820 revpatches = self._revpatches(repo, revs)
820 revpatches = self._revpatches(repo, revs)
821 realpatches += revpatches
821 realpatches += revpatches
822 numrevs = len(revpatches)
822 numrevs = len(revpatches)
823
823
824 self._cleanup(realpatches, numrevs, opts.get('keep'))
824 self._cleanup(realpatches, numrevs, opts.get('keep'))
825
825
826 def checktoppatch(self, repo):
826 def checktoppatch(self, repo):
827 if self.applied:
827 if self.applied:
828 top = self.applied[-1].node
828 top = self.applied[-1].node
829 patch = self.applied[-1].name
829 patch = self.applied[-1].name
830 pp = repo.dirstate.parents()
830 pp = repo.dirstate.parents()
831 if top not in pp:
831 if top not in pp:
832 raise util.Abort(_("working directory revision is not qtip"))
832 raise util.Abort(_("working directory revision is not qtip"))
833 return top, patch
833 return top, patch
834 return None, None
834 return None, None
835
835
836 def checksubstate(self, repo):
836 def checksubstate(self, repo):
837 '''return list of subrepos at a different revision than substate.
837 '''return list of subrepos at a different revision than substate.
838 Abort if any subrepos have uncommitted changes.'''
838 Abort if any subrepos have uncommitted changes.'''
839 inclsubs = []
839 inclsubs = []
840 wctx = repo[None]
840 wctx = repo[None]
841 for s in wctx.substate:
841 for s in wctx.substate:
842 if wctx.sub(s).dirty(True):
842 if wctx.sub(s).dirty(True):
843 raise util.Abort(
843 raise util.Abort(
844 _("uncommitted changes in subrepository %s") % s)
844 _("uncommitted changes in subrepository %s") % s)
845 elif wctx.sub(s).dirty():
845 elif wctx.sub(s).dirty():
846 inclsubs.append(s)
846 inclsubs.append(s)
847 return inclsubs
847 return inclsubs
848
848
849 def localchangesfound(self, refresh=True):
849 def localchangesfound(self, refresh=True):
850 if refresh:
850 if refresh:
851 raise util.Abort(_("local changes found, refresh first"))
851 raise util.Abort(_("local changes found, refresh first"))
852 else:
852 else:
853 raise util.Abort(_("local changes found"))
853 raise util.Abort(_("local changes found"))
854
854
855 def checklocalchanges(self, repo, force=False, refresh=True):
855 def checklocalchanges(self, repo, force=False, refresh=True):
856 m, a, r, d = repo.status()[:4]
856 m, a, r, d = repo.status()[:4]
857 if (m or a or r or d) and not force:
857 if (m or a or r or d) and not force:
858 self.localchangesfound(refresh)
858 self.localchangesfound(refresh)
859 return m, a, r, d
859 return m, a, r, d
860
860
861 _reserved = ('series', 'status', 'guards', '.', '..')
861 _reserved = ('series', 'status', 'guards', '.', '..')
862 def checkreservedname(self, name):
862 def checkreservedname(self, name):
863 if name in self._reserved:
863 if name in self._reserved:
864 raise util.Abort(_('"%s" cannot be used as the name of a patch')
864 raise util.Abort(_('"%s" cannot be used as the name of a patch')
865 % name)
865 % name)
866 for prefix in ('.hg', '.mq'):
866 for prefix in ('.hg', '.mq'):
867 if name.startswith(prefix):
867 if name.startswith(prefix):
868 raise util.Abort(_('patch name cannot begin with "%s"')
868 raise util.Abort(_('patch name cannot begin with "%s"')
869 % prefix)
869 % prefix)
870 for c in ('#', ':'):
870 for c in ('#', ':'):
871 if c in name:
871 if c in name:
872 raise util.Abort(_('"%s" cannot be used in the name of a patch')
872 raise util.Abort(_('"%s" cannot be used in the name of a patch')
873 % c)
873 % c)
874
874
875 def checkpatchname(self, name, force=False):
875 def checkpatchname(self, name, force=False):
876 self.checkreservedname(name)
876 self.checkreservedname(name)
877 if not force and os.path.exists(self.join(name)):
877 if not force and os.path.exists(self.join(name)):
878 if os.path.isdir(self.join(name)):
878 if os.path.isdir(self.join(name)):
879 raise util.Abort(_('"%s" already exists as a directory')
879 raise util.Abort(_('"%s" already exists as a directory')
880 % name)
880 % name)
881 else:
881 else:
882 raise util.Abort(_('patch "%s" already exists') % name)
882 raise util.Abort(_('patch "%s" already exists') % name)
883
883
884 def new(self, repo, patchfn, *pats, **opts):
884 def new(self, repo, patchfn, *pats, **opts):
885 """options:
885 """options:
886 msg: a string or a no-argument function returning a string
886 msg: a string or a no-argument function returning a string
887 """
887 """
888 msg = opts.get('msg')
888 msg = opts.get('msg')
889 user = opts.get('user')
889 user = opts.get('user')
890 date = opts.get('date')
890 date = opts.get('date')
891 if date:
891 if date:
892 date = util.parsedate(date)
892 date = util.parsedate(date)
893 diffopts = self.diffopts({'git': opts.get('git')})
893 diffopts = self.diffopts({'git': opts.get('git')})
894 if opts.get('checkname', True):
894 if opts.get('checkname', True):
895 self.checkpatchname(patchfn)
895 self.checkpatchname(patchfn)
896 inclsubs = self.checksubstate(repo)
896 inclsubs = self.checksubstate(repo)
897 if inclsubs:
897 if inclsubs:
898 inclsubs.append('.hgsubstate')
898 inclsubs.append('.hgsubstate')
899 if opts.get('include') or opts.get('exclude') or pats:
899 if opts.get('include') or opts.get('exclude') or pats:
900 if inclsubs:
900 if inclsubs:
901 pats = list(pats or []) + inclsubs
901 pats = list(pats or []) + inclsubs
902 match = scmutil.match(repo[None], pats, opts)
902 match = scmutil.match(repo[None], pats, opts)
903 # detect missing files in pats
903 # detect missing files in pats
904 def badfn(f, msg):
904 def badfn(f, msg):
905 if f != '.hgsubstate': # .hgsubstate is auto-created
905 if f != '.hgsubstate': # .hgsubstate is auto-created
906 raise util.Abort('%s: %s' % (f, msg))
906 raise util.Abort('%s: %s' % (f, msg))
907 match.bad = badfn
907 match.bad = badfn
908 m, a, r, d = repo.status(match=match)[:4]
908 m, a, r, d = repo.status(match=match)[:4]
909 else:
909 else:
910 m, a, r, d = self.checklocalchanges(repo, force=True)
910 m, a, r, d = self.checklocalchanges(repo, force=True)
911 match = scmutil.matchfiles(repo, m + a + r + inclsubs)
911 match = scmutil.matchfiles(repo, m + a + r + inclsubs)
912 if len(repo[None].parents()) > 1:
912 if len(repo[None].parents()) > 1:
913 raise util.Abort(_('cannot manage merge changesets'))
913 raise util.Abort(_('cannot manage merge changesets'))
914 commitfiles = m + a + r
914 commitfiles = m + a + r
915 self.checktoppatch(repo)
915 self.checktoppatch(repo)
916 insert = self.fullseriesend()
916 insert = self.fullseriesend()
917 wlock = repo.wlock()
917 wlock = repo.wlock()
918 try:
918 try:
919 try:
919 try:
920 # if patch file write fails, abort early
920 # if patch file write fails, abort early
921 p = self.opener(patchfn, "w")
921 p = self.opener(patchfn, "w")
922 except IOError, e:
922 except IOError, e:
923 raise util.Abort(_('cannot write patch "%s": %s')
923 raise util.Abort(_('cannot write patch "%s": %s')
924 % (patchfn, e.strerror))
924 % (patchfn, e.strerror))
925 try:
925 try:
926 if self.plainmode:
926 if self.plainmode:
927 if user:
927 if user:
928 p.write("From: " + user + "\n")
928 p.write("From: " + user + "\n")
929 if not date:
929 if not date:
930 p.write("\n")
930 p.write("\n")
931 if date:
931 if date:
932 p.write("Date: %d %d\n\n" % date)
932 p.write("Date: %d %d\n\n" % date)
933 else:
933 else:
934 p.write("# HG changeset patch\n")
934 p.write("# HG changeset patch\n")
935 p.write("# Parent "
935 p.write("# Parent "
936 + hex(repo[None].p1().node()) + "\n")
936 + hex(repo[None].p1().node()) + "\n")
937 if user:
937 if user:
938 p.write("# User " + user + "\n")
938 p.write("# User " + user + "\n")
939 if date:
939 if date:
940 p.write("# Date %s %s\n\n" % date)
940 p.write("# Date %s %s\n\n" % date)
941 if util.safehasattr(msg, '__call__'):
941 if util.safehasattr(msg, '__call__'):
942 msg = msg()
942 msg = msg()
943 commitmsg = msg and msg or ("[mq]: %s" % patchfn)
943 commitmsg = msg and msg or ("[mq]: %s" % patchfn)
944 n = repo.commit(commitmsg, user, date, match=match, force=True)
944 n = repo.commit(commitmsg, user, date, match=match, force=True)
945 if n is None:
945 if n is None:
946 raise util.Abort(_("repo commit failed"))
946 raise util.Abort(_("repo commit failed"))
947 try:
947 try:
948 self.fullseries[insert:insert] = [patchfn]
948 self.fullseries[insert:insert] = [patchfn]
949 self.applied.append(statusentry(n, patchfn))
949 self.applied.append(statusentry(n, patchfn))
950 self.parseseries()
950 self.parseseries()
951 self.seriesdirty = 1
951 self.seriesdirty = 1
952 self.applieddirty = 1
952 self.applieddirty = 1
953 if msg:
953 if msg:
954 msg = msg + "\n\n"
954 msg = msg + "\n\n"
955 p.write(msg)
955 p.write(msg)
956 if commitfiles:
956 if commitfiles:
957 parent = self.qparents(repo, n)
957 parent = self.qparents(repo, n)
958 chunks = patchmod.diff(repo, node1=parent, node2=n,
958 chunks = patchmod.diff(repo, node1=parent, node2=n,
959 match=match, opts=diffopts)
959 match=match, opts=diffopts)
960 for chunk in chunks:
960 for chunk in chunks:
961 p.write(chunk)
961 p.write(chunk)
962 p.close()
962 p.close()
963 wlock.release()
963 wlock.release()
964 wlock = None
964 wlock = None
965 r = self.qrepo()
965 r = self.qrepo()
966 if r:
966 if r:
967 r[None].add([patchfn])
967 r[None].add([patchfn])
968 except:
968 except:
969 repo.rollback()
969 repo.rollback()
970 raise
970 raise
971 except Exception:
971 except Exception:
972 patchpath = self.join(patchfn)
972 patchpath = self.join(patchfn)
973 try:
973 try:
974 os.unlink(patchpath)
974 os.unlink(patchpath)
975 except:
975 except:
976 self.ui.warn(_('error unlinking %s\n') % patchpath)
976 self.ui.warn(_('error unlinking %s\n') % patchpath)
977 raise
977 raise
978 self.removeundo(repo)
978 self.removeundo(repo)
979 finally:
979 finally:
980 release(wlock)
980 release(wlock)
981
981
982 def strip(self, repo, revs, update=True, backup="all", force=None):
982 def strip(self, repo, revs, update=True, backup="all", force=None):
983 wlock = lock = None
983 wlock = lock = None
984 try:
984 try:
985 wlock = repo.wlock()
985 wlock = repo.wlock()
986 lock = repo.lock()
986 lock = repo.lock()
987
987
988 if update:
988 if update:
989 self.checklocalchanges(repo, force=force, refresh=False)
989 self.checklocalchanges(repo, force=force, refresh=False)
990 urev = self.qparents(repo, revs[0])
990 urev = self.qparents(repo, revs[0])
991 hg.clean(repo, urev)
991 hg.clean(repo, urev)
992 repo.dirstate.write()
992 repo.dirstate.write()
993
993
994 self.removeundo(repo)
994 self.removeundo(repo)
995 for rev in revs:
995 for rev in revs:
996 repair.strip(self.ui, repo, rev, backup)
996 repair.strip(self.ui, repo, rev, backup)
997 # strip may have unbundled a set of backed up revisions after
997 # strip may have unbundled a set of backed up revisions after
998 # the actual strip
998 # the actual strip
999 self.removeundo(repo)
999 self.removeundo(repo)
1000 finally:
1000 finally:
1001 release(lock, wlock)
1001 release(lock, wlock)
1002
1002
1003 def isapplied(self, patch):
1003 def isapplied(self, patch):
1004 """returns (index, rev, patch)"""
1004 """returns (index, rev, patch)"""
1005 for i, a in enumerate(self.applied):
1005 for i, a in enumerate(self.applied):
1006 if a.name == patch:
1006 if a.name == patch:
1007 return (i, a.node, a.name)
1007 return (i, a.node, a.name)
1008 return None
1008 return None
1009
1009
1010 # if the exact patch name does not exist, we try a few
1010 # if the exact patch name does not exist, we try a few
1011 # variations. If strict is passed, we try only #1
1011 # variations. If strict is passed, we try only #1
1012 #
1012 #
1013 # 1) a number to indicate an offset in the series file
1013 # 1) a number to indicate an offset in the series file
1014 # 2) a unique substring of the patch name was given
1014 # 2) a unique substring of the patch name was given
1015 # 3) patchname[-+]num to indicate an offset in the series file
1015 # 3) patchname[-+]num to indicate an offset in the series file
1016 def lookup(self, patch, strict=False):
1016 def lookup(self, patch, strict=False):
1017 patch = patch and str(patch)
1017 patch = patch and str(patch)
1018
1018
1019 def partialname(s):
1019 def partialname(s):
1020 if s in self.series:
1020 if s in self.series:
1021 return s
1021 return s
1022 matches = [x for x in self.series if s in x]
1022 matches = [x for x in self.series if s in x]
1023 if len(matches) > 1:
1023 if len(matches) > 1:
1024 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
1024 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
1025 for m in matches:
1025 for m in matches:
1026 self.ui.warn(' %s\n' % m)
1026 self.ui.warn(' %s\n' % m)
1027 return None
1027 return None
1028 if matches:
1028 if matches:
1029 return matches[0]
1029 return matches[0]
1030 if self.series and self.applied:
1030 if self.series and self.applied:
1031 if s == 'qtip':
1031 if s == 'qtip':
1032 return self.series[self.seriesend(True)-1]
1032 return self.series[self.seriesend(True)-1]
1033 if s == 'qbase':
1033 if s == 'qbase':
1034 return self.series[0]
1034 return self.series[0]
1035 return None
1035 return None
1036
1036
1037 if patch is None:
1037 if patch is None:
1038 return None
1038 return None
1039 if patch in self.series:
1039 if patch in self.series:
1040 return patch
1040 return patch
1041
1041
1042 if not os.path.isfile(self.join(patch)):
1042 if not os.path.isfile(self.join(patch)):
1043 try:
1043 try:
1044 sno = int(patch)
1044 sno = int(patch)
1045 except (ValueError, OverflowError):
1045 except (ValueError, OverflowError):
1046 pass
1046 pass
1047 else:
1047 else:
1048 if -len(self.series) <= sno < len(self.series):
1048 if -len(self.series) <= sno < len(self.series):
1049 return self.series[sno]
1049 return self.series[sno]
1050
1050
1051 if not strict:
1051 if not strict:
1052 res = partialname(patch)
1052 res = partialname(patch)
1053 if res:
1053 if res:
1054 return res
1054 return res
1055 minus = patch.rfind('-')
1055 minus = patch.rfind('-')
1056 if minus >= 0:
1056 if minus >= 0:
1057 res = partialname(patch[:minus])
1057 res = partialname(patch[:minus])
1058 if res:
1058 if res:
1059 i = self.series.index(res)
1059 i = self.series.index(res)
1060 try:
1060 try:
1061 off = int(patch[minus + 1:] or 1)
1061 off = int(patch[minus + 1:] or 1)
1062 except (ValueError, OverflowError):
1062 except (ValueError, OverflowError):
1063 pass
1063 pass
1064 else:
1064 else:
1065 if i - off >= 0:
1065 if i - off >= 0:
1066 return self.series[i - off]
1066 return self.series[i - off]
1067 plus = patch.rfind('+')
1067 plus = patch.rfind('+')
1068 if plus >= 0:
1068 if plus >= 0:
1069 res = partialname(patch[:plus])
1069 res = partialname(patch[:plus])
1070 if res:
1070 if res:
1071 i = self.series.index(res)
1071 i = self.series.index(res)
1072 try:
1072 try:
1073 off = int(patch[plus + 1:] or 1)
1073 off = int(patch[plus + 1:] or 1)
1074 except (ValueError, OverflowError):
1074 except (ValueError, OverflowError):
1075 pass
1075 pass
1076 else:
1076 else:
1077 if i + off < len(self.series):
1077 if i + off < len(self.series):
1078 return self.series[i + off]
1078 return self.series[i + off]
1079 raise util.Abort(_("patch %s not in series") % patch)
1079 raise util.Abort(_("patch %s not in series") % patch)
1080
1080
1081 def push(self, repo, patch=None, force=False, list=False,
1081 def push(self, repo, patch=None, force=False, list=False,
1082 mergeq=None, all=False, move=False, exact=False):
1082 mergeq=None, all=False, move=False, exact=False):
1083 diffopts = self.diffopts()
1083 diffopts = self.diffopts()
1084 wlock = repo.wlock()
1084 wlock = repo.wlock()
1085 try:
1085 try:
1086 heads = []
1086 heads = []
1087 for b, ls in repo.branchmap().iteritems():
1087 for b, ls in repo.branchmap().iteritems():
1088 heads += ls
1088 heads += ls
1089 if not heads:
1089 if not heads:
1090 heads = [nullid]
1090 heads = [nullid]
1091 if repo.dirstate.p1() not in heads and not exact:
1091 if repo.dirstate.p1() not in heads and not exact:
1092 self.ui.status(_("(working directory not at a head)\n"))
1092 self.ui.status(_("(working directory not at a head)\n"))
1093
1093
1094 if not self.series:
1094 if not self.series:
1095 self.ui.warn(_('no patches in series\n'))
1095 self.ui.warn(_('no patches in series\n'))
1096 return 0
1096 return 0
1097
1097
1098 patch = self.lookup(patch)
1098 patch = self.lookup(patch)
1099 # Suppose our series file is: A B C and the current 'top'
1099 # Suppose our series file is: A B C and the current 'top'
1100 # patch is B. qpush C should be performed (moving forward)
1100 # patch is B. qpush C should be performed (moving forward)
1101 # qpush B is a NOP (no change) qpush A is an error (can't
1101 # qpush B is a NOP (no change) qpush A is an error (can't
1102 # go backwards with qpush)
1102 # go backwards with qpush)
1103 if patch:
1103 if patch:
1104 info = self.isapplied(patch)
1104 info = self.isapplied(patch)
1105 if info and info[0] >= len(self.applied) - 1:
1105 if info and info[0] >= len(self.applied) - 1:
1106 self.ui.warn(
1106 self.ui.warn(
1107 _('qpush: %s is already at the top\n') % patch)
1107 _('qpush: %s is already at the top\n') % patch)
1108 return 0
1108 return 0
1109
1109
1110 pushable, reason = self.pushable(patch)
1110 pushable, reason = self.pushable(patch)
1111 if pushable:
1111 if pushable:
1112 if self.series.index(patch) < self.seriesend():
1112 if self.series.index(patch) < self.seriesend():
1113 raise util.Abort(
1113 raise util.Abort(
1114 _("cannot push to a previous patch: %s") % patch)
1114 _("cannot push to a previous patch: %s") % patch)
1115 else:
1115 else:
1116 if reason:
1116 if reason:
1117 reason = _('guarded by %s') % reason
1117 reason = _('guarded by %s') % reason
1118 else:
1118 else:
1119 reason = _('no matching guards')
1119 reason = _('no matching guards')
1120 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1120 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1121 return 1
1121 return 1
1122 elif all:
1122 elif all:
1123 patch = self.series[-1]
1123 patch = self.series[-1]
1124 if self.isapplied(patch):
1124 if self.isapplied(patch):
1125 self.ui.warn(_('all patches are currently applied\n'))
1125 self.ui.warn(_('all patches are currently applied\n'))
1126 return 0
1126 return 0
1127
1127
1128 # Following the above example, starting at 'top' of B:
1128 # Following the above example, starting at 'top' of B:
1129 # qpush should be performed (pushes C), but a subsequent
1129 # qpush should be performed (pushes C), but a subsequent
1130 # qpush without an argument is an error (nothing to
1130 # qpush without an argument is an error (nothing to
1131 # apply). This allows a loop of "...while hg qpush..." to
1131 # apply). This allows a loop of "...while hg qpush..." to
1132 # work as it detects an error when done
1132 # work as it detects an error when done
1133 start = self.seriesend()
1133 start = self.seriesend()
1134 if start == len(self.series):
1134 if start == len(self.series):
1135 self.ui.warn(_('patch series already fully applied\n'))
1135 self.ui.warn(_('patch series already fully applied\n'))
1136 return 1
1136 return 1
1137 if not force:
1137 if not force:
1138 self.checklocalchanges(repo, refresh=self.applied)
1138 self.checklocalchanges(repo, refresh=self.applied)
1139
1139
1140 if exact:
1140 if exact:
1141 if move:
1141 if move:
1142 raise util.Abort(_("cannot use --exact and --move together"))
1142 raise util.Abort(_("cannot use --exact and --move together"))
1143 if self.applied:
1143 if self.applied:
1144 raise util.Abort(_("cannot push --exact with applied patches"))
1144 raise util.Abort(_("cannot push --exact with applied patches"))
1145 root = self.series[start]
1145 root = self.series[start]
1146 target = patchheader(self.join(root), self.plainmode).parent
1146 target = patchheader(self.join(root), self.plainmode).parent
1147 if not target:
1147 if not target:
1148 raise util.Abort(_("%s does not have a parent recorded" % root))
1148 raise util.Abort(_("%s does not have a parent recorded" % root))
1149 if not repo[target] == repo['.']:
1149 if not repo[target] == repo['.']:
1150 hg.update(repo, target)
1150 hg.update(repo, target)
1151
1151
1152 if move:
1152 if move:
1153 if not patch:
1153 if not patch:
1154 raise util.Abort(_("please specify the patch to move"))
1154 raise util.Abort(_("please specify the patch to move"))
1155 for i, rpn in enumerate(self.fullseries[start:]):
1155 for i, rpn in enumerate(self.fullseries[start:]):
1156 # strip markers for patch guards
1156 # strip markers for patch guards
1157 if self.guard_re.split(rpn, 1)[0] == patch:
1157 if self.guard_re.split(rpn, 1)[0] == patch:
1158 break
1158 break
1159 index = start + i
1159 index = start + i
1160 assert index < len(self.fullseries)
1160 assert index < len(self.fullseries)
1161 fullpatch = self.fullseries[index]
1161 fullpatch = self.fullseries[index]
1162 del self.fullseries[index]
1162 del self.fullseries[index]
1163 self.fullseries.insert(start, fullpatch)
1163 self.fullseries.insert(start, fullpatch)
1164 self.parseseries()
1164 self.parseseries()
1165 self.seriesdirty = 1
1165 self.seriesdirty = 1
1166
1166
1167 self.applieddirty = 1
1167 self.applieddirty = 1
1168 if start > 0:
1168 if start > 0:
1169 self.checktoppatch(repo)
1169 self.checktoppatch(repo)
1170 if not patch:
1170 if not patch:
1171 patch = self.series[start]
1171 patch = self.series[start]
1172 end = start + 1
1172 end = start + 1
1173 else:
1173 else:
1174 end = self.series.index(patch, start) + 1
1174 end = self.series.index(patch, start) + 1
1175
1175
1176 s = self.series[start:end]
1176 s = self.series[start:end]
1177 all_files = set()
1177 all_files = set()
1178 try:
1178 try:
1179 if mergeq:
1179 if mergeq:
1180 ret = self.mergepatch(repo, mergeq, s, diffopts)
1180 ret = self.mergepatch(repo, mergeq, s, diffopts)
1181 else:
1181 else:
1182 ret = self.apply(repo, s, list, all_files=all_files)
1182 ret = self.apply(repo, s, list, all_files=all_files)
1183 except:
1183 except:
1184 self.ui.warn(_('cleaning up working directory...'))
1184 self.ui.warn(_('cleaning up working directory...'))
1185 node = repo.dirstate.p1()
1185 node = repo.dirstate.p1()
1186 hg.revert(repo, node, None)
1186 hg.revert(repo, node, None)
1187 # only remove unknown files that we know we touched or
1187 # only remove unknown files that we know we touched or
1188 # created while patching
1188 # created while patching
1189 for f in all_files:
1189 for f in all_files:
1190 if f not in repo.dirstate:
1190 if f not in repo.dirstate:
1191 try:
1191 try:
1192 util.unlinkpath(repo.wjoin(f))
1192 util.unlinkpath(repo.wjoin(f))
1193 except OSError, inst:
1193 except OSError, inst:
1194 if inst.errno != errno.ENOENT:
1194 if inst.errno != errno.ENOENT:
1195 raise
1195 raise
1196 self.ui.warn(_('done\n'))
1196 self.ui.warn(_('done\n'))
1197 raise
1197 raise
1198
1198
1199 if not self.applied:
1199 if not self.applied:
1200 return ret[0]
1200 return ret[0]
1201 top = self.applied[-1].name
1201 top = self.applied[-1].name
1202 if ret[0] and ret[0] > 1:
1202 if ret[0] and ret[0] > 1:
1203 msg = _("errors during apply, please fix and refresh %s\n")
1203 msg = _("errors during apply, please fix and refresh %s\n")
1204 self.ui.write(msg % top)
1204 self.ui.write(msg % top)
1205 else:
1205 else:
1206 self.ui.write(_("now at: %s\n") % top)
1206 self.ui.write(_("now at: %s\n") % top)
1207 return ret[0]
1207 return ret[0]
1208
1208
1209 finally:
1209 finally:
1210 wlock.release()
1210 wlock.release()
1211
1211
1212 def pop(self, repo, patch=None, force=False, update=True, all=False):
1212 def pop(self, repo, patch=None, force=False, update=True, all=False):
1213 wlock = repo.wlock()
1213 wlock = repo.wlock()
1214 try:
1214 try:
1215 if patch:
1215 if patch:
1216 # index, rev, patch
1216 # index, rev, patch
1217 info = self.isapplied(patch)
1217 info = self.isapplied(patch)
1218 if not info:
1218 if not info:
1219 patch = self.lookup(patch)
1219 patch = self.lookup(patch)
1220 info = self.isapplied(patch)
1220 info = self.isapplied(patch)
1221 if not info:
1221 if not info:
1222 raise util.Abort(_("patch %s is not applied") % patch)
1222 raise util.Abort(_("patch %s is not applied") % patch)
1223
1223
1224 if not self.applied:
1224 if not self.applied:
1225 # Allow qpop -a to work repeatedly,
1225 # Allow qpop -a to work repeatedly,
1226 # but not qpop without an argument
1226 # but not qpop without an argument
1227 self.ui.warn(_("no patches applied\n"))
1227 self.ui.warn(_("no patches applied\n"))
1228 return not all
1228 return not all
1229
1229
1230 if all:
1230 if all:
1231 start = 0
1231 start = 0
1232 elif patch:
1232 elif patch:
1233 start = info[0] + 1
1233 start = info[0] + 1
1234 else:
1234 else:
1235 start = len(self.applied) - 1
1235 start = len(self.applied) - 1
1236
1236
1237 if start >= len(self.applied):
1237 if start >= len(self.applied):
1238 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
1238 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
1239 return
1239 return
1240
1240
1241 if not update:
1241 if not update:
1242 parents = repo.dirstate.parents()
1242 parents = repo.dirstate.parents()
1243 rr = [x.node for x in self.applied]
1243 rr = [x.node for x in self.applied]
1244 for p in parents:
1244 for p in parents:
1245 if p in rr:
1245 if p in rr:
1246 self.ui.warn(_("qpop: forcing dirstate update\n"))
1246 self.ui.warn(_("qpop: forcing dirstate update\n"))
1247 update = True
1247 update = True
1248 else:
1248 else:
1249 parents = [p.node() for p in repo[None].parents()]
1249 parents = [p.node() for p in repo[None].parents()]
1250 needupdate = False
1250 needupdate = False
1251 for entry in self.applied[start:]:
1251 for entry in self.applied[start:]:
1252 if entry.node in parents:
1252 if entry.node in parents:
1253 needupdate = True
1253 needupdate = True
1254 break
1254 break
1255 update = needupdate
1255 update = needupdate
1256
1256
1257 if not force and update:
1257 if not force and update:
1258 self.checklocalchanges(repo)
1258 self.checklocalchanges(repo)
1259
1259
1260 self.applieddirty = 1
1260 self.applieddirty = 1
1261 end = len(self.applied)
1261 end = len(self.applied)
1262 rev = self.applied[start].node
1262 rev = self.applied[start].node
1263 if update:
1263 if update:
1264 top = self.checktoppatch(repo)[0]
1264 top = self.checktoppatch(repo)[0]
1265
1265
1266 try:
1266 try:
1267 heads = repo.changelog.heads(rev)
1267 heads = repo.changelog.heads(rev)
1268 except error.LookupError:
1268 except error.LookupError:
1269 node = short(rev)
1269 node = short(rev)
1270 raise util.Abort(_('trying to pop unknown node %s') % node)
1270 raise util.Abort(_('trying to pop unknown node %s') % node)
1271
1271
1272 if heads != [self.applied[-1].node]:
1272 if heads != [self.applied[-1].node]:
1273 raise util.Abort(_("popping would remove a revision not "
1273 raise util.Abort(_("popping would remove a revision not "
1274 "managed by this patch queue"))
1274 "managed by this patch queue"))
1275
1275
1276 # we know there are no local changes, so we can make a simplified
1276 # we know there are no local changes, so we can make a simplified
1277 # form of hg.update.
1277 # form of hg.update.
1278 if update:
1278 if update:
1279 qp = self.qparents(repo, rev)
1279 qp = self.qparents(repo, rev)
1280 ctx = repo[qp]
1280 ctx = repo[qp]
1281 m, a, r, d = repo.status(qp, top)[:4]
1281 m, a, r, d = repo.status(qp, top)[:4]
1282 if d:
1282 if d:
1283 raise util.Abort(_("deletions found between repo revs"))
1283 raise util.Abort(_("deletions found between repo revs"))
1284 for f in a:
1284 for f in a:
1285 try:
1285 try:
1286 util.unlinkpath(repo.wjoin(f))
1286 util.unlinkpath(repo.wjoin(f))
1287 except OSError, e:
1287 except OSError, e:
1288 if e.errno != errno.ENOENT:
1288 if e.errno != errno.ENOENT:
1289 raise
1289 raise
1290 repo.dirstate.drop(f)
1290 repo.dirstate.drop(f)
1291 for f in m + r:
1291 for f in m + r:
1292 fctx = ctx[f]
1292 fctx = ctx[f]
1293 repo.wwrite(f, fctx.data(), fctx.flags())
1293 repo.wwrite(f, fctx.data(), fctx.flags())
1294 repo.dirstate.normal(f)
1294 repo.dirstate.normal(f)
1295 repo.dirstate.setparents(qp, nullid)
1295 repo.dirstate.setparents(qp, nullid)
1296 for patch in reversed(self.applied[start:end]):
1296 for patch in reversed(self.applied[start:end]):
1297 self.ui.status(_("popping %s\n") % patch.name)
1297 self.ui.status(_("popping %s\n") % patch.name)
1298 del self.applied[start:end]
1298 del self.applied[start:end]
1299 self.strip(repo, [rev], update=False, backup='strip')
1299 self.strip(repo, [rev], update=False, backup='strip')
1300 if self.applied:
1300 if self.applied:
1301 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1301 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1302 else:
1302 else:
1303 self.ui.write(_("patch queue now empty\n"))
1303 self.ui.write(_("patch queue now empty\n"))
1304 finally:
1304 finally:
1305 wlock.release()
1305 wlock.release()
1306
1306
1307 def diff(self, repo, pats, opts):
1307 def diff(self, repo, pats, opts):
1308 top, patch = self.checktoppatch(repo)
1308 top, patch = self.checktoppatch(repo)
1309 if not top:
1309 if not top:
1310 self.ui.write(_("no patches applied\n"))
1310 self.ui.write(_("no patches applied\n"))
1311 return
1311 return
1312 qp = self.qparents(repo, top)
1312 qp = self.qparents(repo, top)
1313 if opts.get('reverse'):
1313 if opts.get('reverse'):
1314 node1, node2 = None, qp
1314 node1, node2 = None, qp
1315 else:
1315 else:
1316 node1, node2 = qp, None
1316 node1, node2 = qp, None
1317 diffopts = self.diffopts(opts, patch)
1317 diffopts = self.diffopts(opts, patch)
1318 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1318 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1319
1319
1320 def refresh(self, repo, pats=None, **opts):
1320 def refresh(self, repo, pats=None, **opts):
1321 if not self.applied:
1321 if not self.applied:
1322 self.ui.write(_("no patches applied\n"))
1322 self.ui.write(_("no patches applied\n"))
1323 return 1
1323 return 1
1324 msg = opts.get('msg', '').rstrip()
1324 msg = opts.get('msg', '').rstrip()
1325 newuser = opts.get('user')
1325 newuser = opts.get('user')
1326 newdate = opts.get('date')
1326 newdate = opts.get('date')
1327 if newdate:
1327 if newdate:
1328 newdate = '%d %d' % util.parsedate(newdate)
1328 newdate = '%d %d' % util.parsedate(newdate)
1329 wlock = repo.wlock()
1329 wlock = repo.wlock()
1330
1330
1331 try:
1331 try:
1332 self.checktoppatch(repo)
1332 self.checktoppatch(repo)
1333 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1333 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1334 if repo.changelog.heads(top) != [top]:
1334 if repo.changelog.heads(top) != [top]:
1335 raise util.Abort(_("cannot refresh a revision with children"))
1335 raise util.Abort(_("cannot refresh a revision with children"))
1336
1336
1337 inclsubs = self.checksubstate(repo)
1337 inclsubs = self.checksubstate(repo)
1338
1338
1339 cparents = repo.changelog.parents(top)
1339 cparents = repo.changelog.parents(top)
1340 patchparent = self.qparents(repo, top)
1340 patchparent = self.qparents(repo, top)
1341 ph = patchheader(self.join(patchfn), self.plainmode)
1341 ph = patchheader(self.join(patchfn), self.plainmode)
1342 diffopts = self.diffopts({'git': opts.get('git')}, patchfn)
1342 diffopts = self.diffopts({'git': opts.get('git')}, patchfn)
1343 if msg:
1343 if msg:
1344 ph.setmessage(msg)
1344 ph.setmessage(msg)
1345 if newuser:
1345 if newuser:
1346 ph.setuser(newuser)
1346 ph.setuser(newuser)
1347 if newdate:
1347 if newdate:
1348 ph.setdate(newdate)
1348 ph.setdate(newdate)
1349 ph.setparent(hex(patchparent))
1349 ph.setparent(hex(patchparent))
1350
1350
1351 # only commit new patch when write is complete
1351 # only commit new patch when write is complete
1352 patchf = self.opener(patchfn, 'w', atomictemp=True)
1352 patchf = self.opener(patchfn, 'w', atomictemp=True)
1353
1353
1354 comments = str(ph)
1354 comments = str(ph)
1355 if comments:
1355 if comments:
1356 patchf.write(comments)
1356 patchf.write(comments)
1357
1357
1358 # update the dirstate in place, strip off the qtip commit
1358 # update the dirstate in place, strip off the qtip commit
1359 # and then commit.
1359 # and then commit.
1360 #
1360 #
1361 # this should really read:
1361 # this should really read:
1362 # mm, dd, aa = repo.status(top, patchparent)[:3]
1362 # mm, dd, aa = repo.status(top, patchparent)[:3]
1363 # but we do it backwards to take advantage of manifest/chlog
1363 # but we do it backwards to take advantage of manifest/chlog
1364 # caching against the next repo.status call
1364 # caching against the next repo.status call
1365 mm, aa, dd = repo.status(patchparent, top)[:3]
1365 mm, aa, dd = repo.status(patchparent, top)[:3]
1366 changes = repo.changelog.read(top)
1366 changes = repo.changelog.read(top)
1367 man = repo.manifest.read(changes[0])
1367 man = repo.manifest.read(changes[0])
1368 aaa = aa[:]
1368 aaa = aa[:]
1369 matchfn = scmutil.match(repo[None], pats, opts)
1369 matchfn = scmutil.match(repo[None], pats, opts)
1370 # in short mode, we only diff the files included in the
1370 # in short mode, we only diff the files included in the
1371 # patch already plus specified files
1371 # patch already plus specified files
1372 if opts.get('short'):
1372 if opts.get('short'):
1373 # if amending a patch, we start with existing
1373 # if amending a patch, we start with existing
1374 # files plus specified files - unfiltered
1374 # files plus specified files - unfiltered
1375 match = scmutil.matchfiles(repo, mm + aa + dd + matchfn.files())
1375 match = scmutil.matchfiles(repo, mm + aa + dd + matchfn.files())
1376 # filter with inc/exl options
1376 # filter with inc/exl options
1377 matchfn = scmutil.match(repo[None], opts=opts)
1377 matchfn = scmutil.match(repo[None], opts=opts)
1378 else:
1378 else:
1379 match = scmutil.matchall(repo)
1379 match = scmutil.matchall(repo)
1380 m, a, r, d = repo.status(match=match)[:4]
1380 m, a, r, d = repo.status(match=match)[:4]
1381 mm = set(mm)
1381 mm = set(mm)
1382 aa = set(aa)
1382 aa = set(aa)
1383 dd = set(dd)
1383 dd = set(dd)
1384
1384
1385 # we might end up with files that were added between
1385 # we might end up with files that were added between
1386 # qtip and the dirstate parent, but then changed in the
1386 # qtip and the dirstate parent, but then changed in the
1387 # local dirstate. in this case, we want them to only
1387 # local dirstate. in this case, we want them to only
1388 # show up in the added section
1388 # show up in the added section
1389 for x in m:
1389 for x in m:
1390 if x not in aa:
1390 if x not in aa:
1391 mm.add(x)
1391 mm.add(x)
1392 # we might end up with files added by the local dirstate that
1392 # we might end up with files added by the local dirstate that
1393 # were deleted by the patch. In this case, they should only
1393 # were deleted by the patch. In this case, they should only
1394 # show up in the changed section.
1394 # show up in the changed section.
1395 for x in a:
1395 for x in a:
1396 if x in dd:
1396 if x in dd:
1397 dd.remove(x)
1397 dd.remove(x)
1398 mm.add(x)
1398 mm.add(x)
1399 else:
1399 else:
1400 aa.add(x)
1400 aa.add(x)
1401 # make sure any files deleted in the local dirstate
1401 # make sure any files deleted in the local dirstate
1402 # are not in the add or change column of the patch
1402 # are not in the add or change column of the patch
1403 forget = []
1403 forget = []
1404 for x in d + r:
1404 for x in d + r:
1405 if x in aa:
1405 if x in aa:
1406 aa.remove(x)
1406 aa.remove(x)
1407 forget.append(x)
1407 forget.append(x)
1408 continue
1408 continue
1409 else:
1409 else:
1410 mm.discard(x)
1410 mm.discard(x)
1411 dd.add(x)
1411 dd.add(x)
1412
1412
1413 m = list(mm)
1413 m = list(mm)
1414 r = list(dd)
1414 r = list(dd)
1415 a = list(aa)
1415 a = list(aa)
1416 c = [filter(matchfn, l) for l in (m, a, r)]
1416 c = [filter(matchfn, l) for l in (m, a, r)]
1417 match = scmutil.matchfiles(repo, set(c[0] + c[1] + c[2] + inclsubs))
1417 match = scmutil.matchfiles(repo, set(c[0] + c[1] + c[2] + inclsubs))
1418 chunks = patchmod.diff(repo, patchparent, match=match,
1418 chunks = patchmod.diff(repo, patchparent, match=match,
1419 changes=c, opts=diffopts)
1419 changes=c, opts=diffopts)
1420 for chunk in chunks:
1420 for chunk in chunks:
1421 patchf.write(chunk)
1421 patchf.write(chunk)
1422
1422
1423 try:
1423 try:
1424 if diffopts.git or diffopts.upgrade:
1424 if diffopts.git or diffopts.upgrade:
1425 copies = {}
1425 copies = {}
1426 for dst in a:
1426 for dst in a:
1427 src = repo.dirstate.copied(dst)
1427 src = repo.dirstate.copied(dst)
1428 # during qfold, the source file for copies may
1428 # during qfold, the source file for copies may
1429 # be removed. Treat this as a simple add.
1429 # be removed. Treat this as a simple add.
1430 if src is not None and src in repo.dirstate:
1430 if src is not None and src in repo.dirstate:
1431 copies.setdefault(src, []).append(dst)
1431 copies.setdefault(src, []).append(dst)
1432 repo.dirstate.add(dst)
1432 repo.dirstate.add(dst)
1433 # remember the copies between patchparent and qtip
1433 # remember the copies between patchparent and qtip
1434 for dst in aaa:
1434 for dst in aaa:
1435 f = repo.file(dst)
1435 f = repo.file(dst)
1436 src = f.renamed(man[dst])
1436 src = f.renamed(man[dst])
1437 if src:
1437 if src:
1438 copies.setdefault(src[0], []).extend(
1438 copies.setdefault(src[0], []).extend(
1439 copies.get(dst, []))
1439 copies.get(dst, []))
1440 if dst in a:
1440 if dst in a:
1441 copies[src[0]].append(dst)
1441 copies[src[0]].append(dst)
1442 # we can't copy a file created by the patch itself
1442 # we can't copy a file created by the patch itself
1443 if dst in copies:
1443 if dst in copies:
1444 del copies[dst]
1444 del copies[dst]
1445 for src, dsts in copies.iteritems():
1445 for src, dsts in copies.iteritems():
1446 for dst in dsts:
1446 for dst in dsts:
1447 repo.dirstate.copy(src, dst)
1447 repo.dirstate.copy(src, dst)
1448 else:
1448 else:
1449 for dst in a:
1449 for dst in a:
1450 repo.dirstate.add(dst)
1450 repo.dirstate.add(dst)
1451 # Drop useless copy information
1451 # Drop useless copy information
1452 for f in list(repo.dirstate.copies()):
1452 for f in list(repo.dirstate.copies()):
1453 repo.dirstate.copy(None, f)
1453 repo.dirstate.copy(None, f)
1454 for f in r:
1454 for f in r:
1455 repo.dirstate.remove(f)
1455 repo.dirstate.remove(f)
1456 # if the patch excludes a modified file, mark that
1456 # if the patch excludes a modified file, mark that
1457 # file with mtime=0 so status can see it.
1457 # file with mtime=0 so status can see it.
1458 mm = []
1458 mm = []
1459 for i in xrange(len(m)-1, -1, -1):
1459 for i in xrange(len(m)-1, -1, -1):
1460 if not matchfn(m[i]):
1460 if not matchfn(m[i]):
1461 mm.append(m[i])
1461 mm.append(m[i])
1462 del m[i]
1462 del m[i]
1463 for f in m:
1463 for f in m:
1464 repo.dirstate.normal(f)
1464 repo.dirstate.normal(f)
1465 for f in mm:
1465 for f in mm:
1466 repo.dirstate.normallookup(f)
1466 repo.dirstate.normallookup(f)
1467 for f in forget:
1467 for f in forget:
1468 repo.dirstate.drop(f)
1468 repo.dirstate.drop(f)
1469
1469
1470 if not msg:
1470 if not msg:
1471 if not ph.message:
1471 if not ph.message:
1472 message = "[mq]: %s\n" % patchfn
1472 message = "[mq]: %s\n" % patchfn
1473 else:
1473 else:
1474 message = "\n".join(ph.message)
1474 message = "\n".join(ph.message)
1475 else:
1475 else:
1476 message = msg
1476 message = msg
1477
1477
1478 user = ph.user or changes[1]
1478 user = ph.user or changes[1]
1479
1479
1480 # assumes strip can roll itself back if interrupted
1480 # assumes strip can roll itself back if interrupted
1481 repo.dirstate.setparents(*cparents)
1481 repo.dirstate.setparents(*cparents)
1482 self.applied.pop()
1482 self.applied.pop()
1483 self.applieddirty = 1
1483 self.applieddirty = 1
1484 self.strip(repo, [top], update=False,
1484 self.strip(repo, [top], update=False,
1485 backup='strip')
1485 backup='strip')
1486 except:
1486 except:
1487 repo.dirstate.invalidate()
1487 repo.dirstate.invalidate()
1488 raise
1488 raise
1489
1489
1490 try:
1490 try:
1491 # might be nice to attempt to roll back strip after this
1491 # might be nice to attempt to roll back strip after this
1492 n = repo.commit(message, user, ph.date, match=match,
1492 n = repo.commit(message, user, ph.date, match=match,
1493 force=True)
1493 force=True)
1494 # only write patch after a successful commit
1494 # only write patch after a successful commit
1495 patchf.rename()
1495 patchf.rename()
1496 self.applied.append(statusentry(n, patchfn))
1496 self.applied.append(statusentry(n, patchfn))
1497 except:
1497 except:
1498 ctx = repo[cparents[0]]
1498 ctx = repo[cparents[0]]
1499 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1499 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1500 self.savedirty()
1500 self.savedirty()
1501 self.ui.warn(_('refresh interrupted while patch was popped! '
1501 self.ui.warn(_('refresh interrupted while patch was popped! '
1502 '(revert --all, qpush to recover)\n'))
1502 '(revert --all, qpush to recover)\n'))
1503 raise
1503 raise
1504 finally:
1504 finally:
1505 wlock.release()
1505 wlock.release()
1506 self.removeundo(repo)
1506 self.removeundo(repo)
1507
1507
1508 def init(self, repo, create=False):
1508 def init(self, repo, create=False):
1509 if not create and os.path.isdir(self.path):
1509 if not create and os.path.isdir(self.path):
1510 raise util.Abort(_("patch queue directory already exists"))
1510 raise util.Abort(_("patch queue directory already exists"))
1511 try:
1511 try:
1512 os.mkdir(self.path)
1512 os.mkdir(self.path)
1513 except OSError, inst:
1513 except OSError, inst:
1514 if inst.errno != errno.EEXIST or not create:
1514 if inst.errno != errno.EEXIST or not create:
1515 raise
1515 raise
1516 if create:
1516 if create:
1517 return self.qrepo(create=True)
1517 return self.qrepo(create=True)
1518
1518
1519 def unapplied(self, repo, patch=None):
1519 def unapplied(self, repo, patch=None):
1520 if patch and patch not in self.series:
1520 if patch and patch not in self.series:
1521 raise util.Abort(_("patch %s is not in series file") % patch)
1521 raise util.Abort(_("patch %s is not in series file") % patch)
1522 if not patch:
1522 if not patch:
1523 start = self.seriesend()
1523 start = self.seriesend()
1524 else:
1524 else:
1525 start = self.series.index(patch) + 1
1525 start = self.series.index(patch) + 1
1526 unapplied = []
1526 unapplied = []
1527 for i in xrange(start, len(self.series)):
1527 for i in xrange(start, len(self.series)):
1528 pushable, reason = self.pushable(i)
1528 pushable, reason = self.pushable(i)
1529 if pushable:
1529 if pushable:
1530 unapplied.append((i, self.series[i]))
1530 unapplied.append((i, self.series[i]))
1531 self.explainpushable(i)
1531 self.explainpushable(i)
1532 return unapplied
1532 return unapplied
1533
1533
1534 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1534 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1535 summary=False):
1535 summary=False):
1536 def displayname(pfx, patchname, state):
1536 def displayname(pfx, patchname, state):
1537 if pfx:
1537 if pfx:
1538 self.ui.write(pfx)
1538 self.ui.write(pfx)
1539 if summary:
1539 if summary:
1540 ph = patchheader(self.join(patchname), self.plainmode)
1540 ph = patchheader(self.join(patchname), self.plainmode)
1541 msg = ph.message and ph.message[0] or ''
1541 msg = ph.message and ph.message[0] or ''
1542 if self.ui.formatted():
1542 if self.ui.formatted():
1543 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
1543 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
1544 if width > 0:
1544 if width > 0:
1545 msg = util.ellipsis(msg, width)
1545 msg = util.ellipsis(msg, width)
1546 else:
1546 else:
1547 msg = ''
1547 msg = ''
1548 self.ui.write(patchname, label='qseries.' + state)
1548 self.ui.write(patchname, label='qseries.' + state)
1549 self.ui.write(': ')
1549 self.ui.write(': ')
1550 self.ui.write(msg, label='qseries.message.' + state)
1550 self.ui.write(msg, label='qseries.message.' + state)
1551 else:
1551 else:
1552 self.ui.write(patchname, label='qseries.' + state)
1552 self.ui.write(patchname, label='qseries.' + state)
1553 self.ui.write('\n')
1553 self.ui.write('\n')
1554
1554
1555 applied = set([p.name for p in self.applied])
1555 applied = set([p.name for p in self.applied])
1556 if length is None:
1556 if length is None:
1557 length = len(self.series) - start
1557 length = len(self.series) - start
1558 if not missing:
1558 if not missing:
1559 if self.ui.verbose:
1559 if self.ui.verbose:
1560 idxwidth = len(str(start + length - 1))
1560 idxwidth = len(str(start + length - 1))
1561 for i in xrange(start, start + length):
1561 for i in xrange(start, start + length):
1562 patch = self.series[i]
1562 patch = self.series[i]
1563 if patch in applied:
1563 if patch in applied:
1564 char, state = 'A', 'applied'
1564 char, state = 'A', 'applied'
1565 elif self.pushable(i)[0]:
1565 elif self.pushable(i)[0]:
1566 char, state = 'U', 'unapplied'
1566 char, state = 'U', 'unapplied'
1567 else:
1567 else:
1568 char, state = 'G', 'guarded'
1568 char, state = 'G', 'guarded'
1569 pfx = ''
1569 pfx = ''
1570 if self.ui.verbose:
1570 if self.ui.verbose:
1571 pfx = '%*d %s ' % (idxwidth, i, char)
1571 pfx = '%*d %s ' % (idxwidth, i, char)
1572 elif status and status != char:
1572 elif status and status != char:
1573 continue
1573 continue
1574 displayname(pfx, patch, state)
1574 displayname(pfx, patch, state)
1575 else:
1575 else:
1576 msng_list = []
1576 msng_list = []
1577 for root, dirs, files in os.walk(self.path):
1577 for root, dirs, files in os.walk(self.path):
1578 d = root[len(self.path) + 1:]
1578 d = root[len(self.path) + 1:]
1579 for f in files:
1579 for f in files:
1580 fl = os.path.join(d, f)
1580 fl = os.path.join(d, f)
1581 if (fl not in self.series and
1581 if (fl not in self.series and
1582 fl not in (self.statuspath, self.seriespath,
1582 fl not in (self.statuspath, self.seriespath,
1583 self.guardspath)
1583 self.guardspath)
1584 and not fl.startswith('.')):
1584 and not fl.startswith('.')):
1585 msng_list.append(fl)
1585 msng_list.append(fl)
1586 for x in sorted(msng_list):
1586 for x in sorted(msng_list):
1587 pfx = self.ui.verbose and ('D ') or ''
1587 pfx = self.ui.verbose and ('D ') or ''
1588 displayname(pfx, x, 'missing')
1588 displayname(pfx, x, 'missing')
1589
1589
1590 def issaveline(self, l):
1590 def issaveline(self, l):
1591 if l.name == '.hg.patches.save.line':
1591 if l.name == '.hg.patches.save.line':
1592 return True
1592 return True
1593
1593
1594 def qrepo(self, create=False):
1594 def qrepo(self, create=False):
1595 ui = self.ui.copy()
1595 ui = self.ui.copy()
1596 ui.setconfig('paths', 'default', '', overlay=False)
1596 ui.setconfig('paths', 'default', '', overlay=False)
1597 ui.setconfig('paths', 'default-push', '', overlay=False)
1597 ui.setconfig('paths', 'default-push', '', overlay=False)
1598 if create or os.path.isdir(self.join(".hg")):
1598 if create or os.path.isdir(self.join(".hg")):
1599 return hg.repository(ui, path=self.path, create=create)
1599 return hg.repository(ui, path=self.path, create=create)
1600
1600
1601 def restore(self, repo, rev, delete=None, qupdate=None):
1601 def restore(self, repo, rev, delete=None, qupdate=None):
1602 desc = repo[rev].description().strip()
1602 desc = repo[rev].description().strip()
1603 lines = desc.splitlines()
1603 lines = desc.splitlines()
1604 i = 0
1604 i = 0
1605 datastart = None
1605 datastart = None
1606 series = []
1606 series = []
1607 applied = []
1607 applied = []
1608 qpp = None
1608 qpp = None
1609 for i, line in enumerate(lines):
1609 for i, line in enumerate(lines):
1610 if line == 'Patch Data:':
1610 if line == 'Patch Data:':
1611 datastart = i + 1
1611 datastart = i + 1
1612 elif line.startswith('Dirstate:'):
1612 elif line.startswith('Dirstate:'):
1613 l = line.rstrip()
1613 l = line.rstrip()
1614 l = l[10:].split(' ')
1614 l = l[10:].split(' ')
1615 qpp = [bin(x) for x in l]
1615 qpp = [bin(x) for x in l]
1616 elif datastart is not None:
1616 elif datastart is not None:
1617 l = line.rstrip()
1617 l = line.rstrip()
1618 n, name = l.split(':', 1)
1618 n, name = l.split(':', 1)
1619 if n:
1619 if n:
1620 applied.append(statusentry(bin(n), name))
1620 applied.append(statusentry(bin(n), name))
1621 else:
1621 else:
1622 series.append(l)
1622 series.append(l)
1623 if datastart is None:
1623 if datastart is None:
1624 self.ui.warn(_("No saved patch data found\n"))
1624 self.ui.warn(_("No saved patch data found\n"))
1625 return 1
1625 return 1
1626 self.ui.warn(_("restoring status: %s\n") % lines[0])
1626 self.ui.warn(_("restoring status: %s\n") % lines[0])
1627 self.fullseries = series
1627 self.fullseries = series
1628 self.applied = applied
1628 self.applied = applied
1629 self.parseseries()
1629 self.parseseries()
1630 self.seriesdirty = 1
1630 self.seriesdirty = 1
1631 self.applieddirty = 1
1631 self.applieddirty = 1
1632 heads = repo.changelog.heads()
1632 heads = repo.changelog.heads()
1633 if delete:
1633 if delete:
1634 if rev not in heads:
1634 if rev not in heads:
1635 self.ui.warn(_("save entry has children, leaving it alone\n"))
1635 self.ui.warn(_("save entry has children, leaving it alone\n"))
1636 else:
1636 else:
1637 self.ui.warn(_("removing save entry %s\n") % short(rev))
1637 self.ui.warn(_("removing save entry %s\n") % short(rev))
1638 pp = repo.dirstate.parents()
1638 pp = repo.dirstate.parents()
1639 if rev in pp:
1639 if rev in pp:
1640 update = True
1640 update = True
1641 else:
1641 else:
1642 update = False
1642 update = False
1643 self.strip(repo, [rev], update=update, backup='strip')
1643 self.strip(repo, [rev], update=update, backup='strip')
1644 if qpp:
1644 if qpp:
1645 self.ui.warn(_("saved queue repository parents: %s %s\n") %
1645 self.ui.warn(_("saved queue repository parents: %s %s\n") %
1646 (short(qpp[0]), short(qpp[1])))
1646 (short(qpp[0]), short(qpp[1])))
1647 if qupdate:
1647 if qupdate:
1648 self.ui.status(_("updating queue directory\n"))
1648 self.ui.status(_("updating queue directory\n"))
1649 r = self.qrepo()
1649 r = self.qrepo()
1650 if not r:
1650 if not r:
1651 self.ui.warn(_("Unable to load queue repository\n"))
1651 self.ui.warn(_("Unable to load queue repository\n"))
1652 return 1
1652 return 1
1653 hg.clean(r, qpp[0])
1653 hg.clean(r, qpp[0])
1654
1654
1655 def save(self, repo, msg=None):
1655 def save(self, repo, msg=None):
1656 if not self.applied:
1656 if not self.applied:
1657 self.ui.warn(_("save: no patches applied, exiting\n"))
1657 self.ui.warn(_("save: no patches applied, exiting\n"))
1658 return 1
1658 return 1
1659 if self.issaveline(self.applied[-1]):
1659 if self.issaveline(self.applied[-1]):
1660 self.ui.warn(_("status is already saved\n"))
1660 self.ui.warn(_("status is already saved\n"))
1661 return 1
1661 return 1
1662
1662
1663 if not msg:
1663 if not msg:
1664 msg = _("hg patches saved state")
1664 msg = _("hg patches saved state")
1665 else:
1665 else:
1666 msg = "hg patches: " + msg.rstrip('\r\n')
1666 msg = "hg patches: " + msg.rstrip('\r\n')
1667 r = self.qrepo()
1667 r = self.qrepo()
1668 if r:
1668 if r:
1669 pp = r.dirstate.parents()
1669 pp = r.dirstate.parents()
1670 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1670 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1671 msg += "\n\nPatch Data:\n"
1671 msg += "\n\nPatch Data:\n"
1672 msg += ''.join('%s\n' % x for x in self.applied)
1672 msg += ''.join('%s\n' % x for x in self.applied)
1673 msg += ''.join(':%s\n' % x for x in self.fullseries)
1673 msg += ''.join(':%s\n' % x for x in self.fullseries)
1674 n = repo.commit(msg, force=True)
1674 n = repo.commit(msg, force=True)
1675 if not n:
1675 if not n:
1676 self.ui.warn(_("repo commit failed\n"))
1676 self.ui.warn(_("repo commit failed\n"))
1677 return 1
1677 return 1
1678 self.applied.append(statusentry(n, '.hg.patches.save.line'))
1678 self.applied.append(statusentry(n, '.hg.patches.save.line'))
1679 self.applieddirty = 1
1679 self.applieddirty = 1
1680 self.removeundo(repo)
1680 self.removeundo(repo)
1681
1681
1682 def fullseriesend(self):
1682 def fullseriesend(self):
1683 if self.applied:
1683 if self.applied:
1684 p = self.applied[-1].name
1684 p = self.applied[-1].name
1685 end = self.findseries(p)
1685 end = self.findseries(p)
1686 if end is None:
1686 if end is None:
1687 return len(self.fullseries)
1687 return len(self.fullseries)
1688 return end + 1
1688 return end + 1
1689 return 0
1689 return 0
1690
1690
1691 def seriesend(self, all_patches=False):
1691 def seriesend(self, all_patches=False):
1692 """If all_patches is False, return the index of the next pushable patch
1692 """If all_patches is False, return the index of the next pushable patch
1693 in the series, or the series length. If all_patches is True, return the
1693 in the series, or the series length. If all_patches is True, return the
1694 index of the first patch past the last applied one.
1694 index of the first patch past the last applied one.
1695 """
1695 """
1696 end = 0
1696 end = 0
1697 def next(start):
1697 def next(start):
1698 if all_patches or start >= len(self.series):
1698 if all_patches or start >= len(self.series):
1699 return start
1699 return start
1700 for i in xrange(start, len(self.series)):
1700 for i in xrange(start, len(self.series)):
1701 p, reason = self.pushable(i)
1701 p, reason = self.pushable(i)
1702 if p:
1702 if p:
1703 break
1703 break
1704 self.explainpushable(i)
1704 self.explainpushable(i)
1705 return i
1705 return i
1706 if self.applied:
1706 if self.applied:
1707 p = self.applied[-1].name
1707 p = self.applied[-1].name
1708 try:
1708 try:
1709 end = self.series.index(p)
1709 end = self.series.index(p)
1710 except ValueError:
1710 except ValueError:
1711 return 0
1711 return 0
1712 return next(end + 1)
1712 return next(end + 1)
1713 return next(end)
1713 return next(end)
1714
1714
1715 def appliedname(self, index):
1715 def appliedname(self, index):
1716 pname = self.applied[index].name
1716 pname = self.applied[index].name
1717 if not self.ui.verbose:
1717 if not self.ui.verbose:
1718 p = pname
1718 p = pname
1719 else:
1719 else:
1720 p = str(self.series.index(pname)) + " " + pname
1720 p = str(self.series.index(pname)) + " " + pname
1721 return p
1721 return p
1722
1722
1723 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1723 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1724 force=None, git=False):
1724 force=None, git=False):
1725 def checkseries(patchname):
1725 def checkseries(patchname):
1726 if patchname in self.series:
1726 if patchname in self.series:
1727 raise util.Abort(_('patch %s is already in the series file')
1727 raise util.Abort(_('patch %s is already in the series file')
1728 % patchname)
1728 % patchname)
1729
1729
1730 if rev:
1730 if rev:
1731 if files:
1731 if files:
1732 raise util.Abort(_('option "-r" not valid when importing '
1732 raise util.Abort(_('option "-r" not valid when importing '
1733 'files'))
1733 'files'))
1734 rev = scmutil.revrange(repo, rev)
1734 rev = scmutil.revrange(repo, rev)
1735 rev.sort(reverse=True)
1735 rev.sort(reverse=True)
1736 if (len(files) > 1 or len(rev) > 1) and patchname:
1736 if (len(files) > 1 or len(rev) > 1) and patchname:
1737 raise util.Abort(_('option "-n" not valid when importing multiple '
1737 raise util.Abort(_('option "-n" not valid when importing multiple '
1738 'patches'))
1738 'patches'))
1739 if rev:
1739 if rev:
1740 # If mq patches are applied, we can only import revisions
1740 # If mq patches are applied, we can only import revisions
1741 # that form a linear path to qbase.
1741 # that form a linear path to qbase.
1742 # Otherwise, they should form a linear path to a head.
1742 # Otherwise, they should form a linear path to a head.
1743 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1743 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1744 if len(heads) > 1:
1744 if len(heads) > 1:
1745 raise util.Abort(_('revision %d is the root of more than one '
1745 raise util.Abort(_('revision %d is the root of more than one '
1746 'branch') % rev[-1])
1746 'branch') % rev[-1])
1747 if self.applied:
1747 if self.applied:
1748 base = repo.changelog.node(rev[0])
1748 base = repo.changelog.node(rev[0])
1749 if base in [n.node for n in self.applied]:
1749 if base in [n.node for n in self.applied]:
1750 raise util.Abort(_('revision %d is already managed')
1750 raise util.Abort(_('revision %d is already managed')
1751 % rev[0])
1751 % rev[0])
1752 if heads != [self.applied[-1].node]:
1752 if heads != [self.applied[-1].node]:
1753 raise util.Abort(_('revision %d is not the parent of '
1753 raise util.Abort(_('revision %d is not the parent of '
1754 'the queue') % rev[0])
1754 'the queue') % rev[0])
1755 base = repo.changelog.rev(self.applied[0].node)
1755 base = repo.changelog.rev(self.applied[0].node)
1756 lastparent = repo.changelog.parentrevs(base)[0]
1756 lastparent = repo.changelog.parentrevs(base)[0]
1757 else:
1757 else:
1758 if heads != [repo.changelog.node(rev[0])]:
1758 if heads != [repo.changelog.node(rev[0])]:
1759 raise util.Abort(_('revision %d has unmanaged children')
1759 raise util.Abort(_('revision %d has unmanaged children')
1760 % rev[0])
1760 % rev[0])
1761 lastparent = None
1761 lastparent = None
1762
1762
1763 diffopts = self.diffopts({'git': git})
1763 diffopts = self.diffopts({'git': git})
1764 for r in rev:
1764 for r in rev:
1765 p1, p2 = repo.changelog.parentrevs(r)
1765 p1, p2 = repo.changelog.parentrevs(r)
1766 n = repo.changelog.node(r)
1766 n = repo.changelog.node(r)
1767 if p2 != nullrev:
1767 if p2 != nullrev:
1768 raise util.Abort(_('cannot import merge revision %d') % r)
1768 raise util.Abort(_('cannot import merge revision %d') % r)
1769 if lastparent and lastparent != r:
1769 if lastparent and lastparent != r:
1770 raise util.Abort(_('revision %d is not the parent of %d')
1770 raise util.Abort(_('revision %d is not the parent of %d')
1771 % (r, lastparent))
1771 % (r, lastparent))
1772 lastparent = p1
1772 lastparent = p1
1773
1773
1774 if not patchname:
1774 if not patchname:
1775 patchname = normname('%d.diff' % r)
1775 patchname = normname('%d.diff' % r)
1776 checkseries(patchname)
1776 checkseries(patchname)
1777 self.checkpatchname(patchname, force)
1777 self.checkpatchname(patchname, force)
1778 self.fullseries.insert(0, patchname)
1778 self.fullseries.insert(0, patchname)
1779
1779
1780 patchf = self.opener(patchname, "w")
1780 patchf = self.opener(patchname, "w")
1781 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
1781 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
1782 patchf.close()
1782 patchf.close()
1783
1783
1784 se = statusentry(n, patchname)
1784 se = statusentry(n, patchname)
1785 self.applied.insert(0, se)
1785 self.applied.insert(0, se)
1786
1786
1787 self.added.append(patchname)
1787 self.added.append(patchname)
1788 patchname = None
1788 patchname = None
1789 self.parseseries()
1789 self.parseseries()
1790 self.applieddirty = 1
1790 self.applieddirty = 1
1791 self.seriesdirty = True
1791 self.seriesdirty = True
1792
1792
1793 for i, filename in enumerate(files):
1793 for i, filename in enumerate(files):
1794 if existing:
1794 if existing:
1795 if filename == '-':
1795 if filename == '-':
1796 raise util.Abort(_('-e is incompatible with import from -'))
1796 raise util.Abort(_('-e is incompatible with import from -'))
1797 filename = normname(filename)
1797 filename = normname(filename)
1798 self.checkreservedname(filename)
1798 self.checkreservedname(filename)
1799 originpath = self.join(filename)
1799 originpath = self.join(filename)
1800 if not os.path.isfile(originpath):
1800 if not os.path.isfile(originpath):
1801 raise util.Abort(_("patch %s does not exist") % filename)
1801 raise util.Abort(_("patch %s does not exist") % filename)
1802
1802
1803 if patchname:
1803 if patchname:
1804 self.checkpatchname(patchname, force)
1804 self.checkpatchname(patchname, force)
1805
1805
1806 self.ui.write(_('renaming %s to %s\n')
1806 self.ui.write(_('renaming %s to %s\n')
1807 % (filename, patchname))
1807 % (filename, patchname))
1808 util.rename(originpath, self.join(patchname))
1808 util.rename(originpath, self.join(patchname))
1809 else:
1809 else:
1810 patchname = filename
1810 patchname = filename
1811
1811
1812 else:
1812 else:
1813 if filename == '-' and not patchname:
1813 if filename == '-' and not patchname:
1814 raise util.Abort(_('need --name to import a patch from -'))
1814 raise util.Abort(_('need --name to import a patch from -'))
1815 elif not patchname:
1815 elif not patchname:
1816 patchname = normname(os.path.basename(filename.rstrip('/')))
1816 patchname = normname(os.path.basename(filename.rstrip('/')))
1817 self.checkpatchname(patchname, force)
1817 self.checkpatchname(patchname, force)
1818 try:
1818 try:
1819 if filename == '-':
1819 if filename == '-':
1820 text = self.ui.fin.read()
1820 text = self.ui.fin.read()
1821 else:
1821 else:
1822 fp = url.open(self.ui, filename)
1822 fp = url.open(self.ui, filename)
1823 text = fp.read()
1823 text = fp.read()
1824 fp.close()
1824 fp.close()
1825 except (OSError, IOError):
1825 except (OSError, IOError):
1826 raise util.Abort(_("unable to read file %s") % filename)
1826 raise util.Abort(_("unable to read file %s") % filename)
1827 patchf = self.opener(patchname, "w")
1827 patchf = self.opener(patchname, "w")
1828 patchf.write(text)
1828 patchf.write(text)
1829 patchf.close()
1829 patchf.close()
1830 if not force:
1830 if not force:
1831 checkseries(patchname)
1831 checkseries(patchname)
1832 if patchname not in self.series:
1832 if patchname not in self.series:
1833 index = self.fullseriesend() + i
1833 index = self.fullseriesend() + i
1834 self.fullseries[index:index] = [patchname]
1834 self.fullseries[index:index] = [patchname]
1835 self.parseseries()
1835 self.parseseries()
1836 self.seriesdirty = True
1836 self.seriesdirty = True
1837 self.ui.warn(_("adding %s to series file\n") % patchname)
1837 self.ui.warn(_("adding %s to series file\n") % patchname)
1838 self.added.append(patchname)
1838 self.added.append(patchname)
1839 patchname = None
1839 patchname = None
1840
1840
1841 self.removeundo(repo)
1841 self.removeundo(repo)
1842
1842
1843 @command("qdelete|qremove|qrm",
1843 @command("qdelete|qremove|qrm",
1844 [('k', 'keep', None, _('keep patch file')),
1844 [('k', 'keep', None, _('keep patch file')),
1845 ('r', 'rev', [],
1845 ('r', 'rev', [],
1846 _('stop managing a revision (DEPRECATED)'), _('REV'))],
1846 _('stop managing a revision (DEPRECATED)'), _('REV'))],
1847 _('hg qdelete [-k] [PATCH]...'))
1847 _('hg qdelete [-k] [PATCH]...'))
1848 def delete(ui, repo, *patches, **opts):
1848 def delete(ui, repo, *patches, **opts):
1849 """remove patches from queue
1849 """remove patches from queue
1850
1850
1851 The patches must not be applied, and at least one patch is required. With
1851 The patches must not be applied, and at least one patch is required. With
1852 -k/--keep, the patch files are preserved in the patch directory.
1852 -k/--keep, the patch files are preserved in the patch directory.
1853
1853
1854 To stop managing a patch and move it into permanent history,
1854 To stop managing a patch and move it into permanent history,
1855 use the :hg:`qfinish` command."""
1855 use the :hg:`qfinish` command."""
1856 q = repo.mq
1856 q = repo.mq
1857 q.delete(repo, patches, opts)
1857 q.delete(repo, patches, opts)
1858 q.savedirty()
1858 q.savedirty()
1859 return 0
1859 return 0
1860
1860
1861 @command("qapplied",
1861 @command("qapplied",
1862 [('1', 'last', None, _('show only the last patch'))
1862 [('1', 'last', None, _('show only the last patch'))
1863 ] + seriesopts,
1863 ] + seriesopts,
1864 _('hg qapplied [-1] [-s] [PATCH]'))
1864 _('hg qapplied [-1] [-s] [PATCH]'))
1865 def applied(ui, repo, patch=None, **opts):
1865 def applied(ui, repo, patch=None, **opts):
1866 """print the patches already applied
1866 """print the patches already applied
1867
1867
1868 Returns 0 on success."""
1868 Returns 0 on success."""
1869
1869
1870 q = repo.mq
1870 q = repo.mq
1871
1871
1872 if patch:
1872 if patch:
1873 if patch not in q.series:
1873 if patch not in q.series:
1874 raise util.Abort(_("patch %s is not in series file") % patch)
1874 raise util.Abort(_("patch %s is not in series file") % patch)
1875 end = q.series.index(patch) + 1
1875 end = q.series.index(patch) + 1
1876 else:
1876 else:
1877 end = q.seriesend(True)
1877 end = q.seriesend(True)
1878
1878
1879 if opts.get('last') and not end:
1879 if opts.get('last') and not end:
1880 ui.write(_("no patches applied\n"))
1880 ui.write(_("no patches applied\n"))
1881 return 1
1881 return 1
1882 elif opts.get('last') and end == 1:
1882 elif opts.get('last') and end == 1:
1883 ui.write(_("only one patch applied\n"))
1883 ui.write(_("only one patch applied\n"))
1884 return 1
1884 return 1
1885 elif opts.get('last'):
1885 elif opts.get('last'):
1886 start = end - 2
1886 start = end - 2
1887 end = 1
1887 end = 1
1888 else:
1888 else:
1889 start = 0
1889 start = 0
1890
1890
1891 q.qseries(repo, length=end, start=start, status='A',
1891 q.qseries(repo, length=end, start=start, status='A',
1892 summary=opts.get('summary'))
1892 summary=opts.get('summary'))
1893
1893
1894
1894
1895 @command("qunapplied",
1895 @command("qunapplied",
1896 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
1896 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
1897 _('hg qunapplied [-1] [-s] [PATCH]'))
1897 _('hg qunapplied [-1] [-s] [PATCH]'))
1898 def unapplied(ui, repo, patch=None, **opts):
1898 def unapplied(ui, repo, patch=None, **opts):
1899 """print the patches not yet applied
1899 """print the patches not yet applied
1900
1900
1901 Returns 0 on success."""
1901 Returns 0 on success."""
1902
1902
1903 q = repo.mq
1903 q = repo.mq
1904 if patch:
1904 if patch:
1905 if patch not in q.series:
1905 if patch not in q.series:
1906 raise util.Abort(_("patch %s is not in series file") % patch)
1906 raise util.Abort(_("patch %s is not in series file") % patch)
1907 start = q.series.index(patch) + 1
1907 start = q.series.index(patch) + 1
1908 else:
1908 else:
1909 start = q.seriesend(True)
1909 start = q.seriesend(True)
1910
1910
1911 if start == len(q.series) and opts.get('first'):
1911 if start == len(q.series) and opts.get('first'):
1912 ui.write(_("all patches applied\n"))
1912 ui.write(_("all patches applied\n"))
1913 return 1
1913 return 1
1914
1914
1915 length = opts.get('first') and 1 or None
1915 length = opts.get('first') and 1 or None
1916 q.qseries(repo, start=start, length=length, status='U',
1916 q.qseries(repo, start=start, length=length, status='U',
1917 summary=opts.get('summary'))
1917 summary=opts.get('summary'))
1918
1918
1919 @command("qimport",
1919 @command("qimport",
1920 [('e', 'existing', None, _('import file in patch directory')),
1920 [('e', 'existing', None, _('import file in patch directory')),
1921 ('n', 'name', '',
1921 ('n', 'name', '',
1922 _('name of patch file'), _('NAME')),
1922 _('name of patch file'), _('NAME')),
1923 ('f', 'force', None, _('overwrite existing files')),
1923 ('f', 'force', None, _('overwrite existing files')),
1924 ('r', 'rev', [],
1924 ('r', 'rev', [],
1925 _('place existing revisions under mq control'), _('REV')),
1925 _('place existing revisions under mq control'), _('REV')),
1926 ('g', 'git', None, _('use git extended diff format')),
1926 ('g', 'git', None, _('use git extended diff format')),
1927 ('P', 'push', None, _('qpush after importing'))],
1927 ('P', 'push', None, _('qpush after importing'))],
1928 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... FILE...'))
1928 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... FILE...'))
1929 def qimport(ui, repo, *filename, **opts):
1929 def qimport(ui, repo, *filename, **opts):
1930 """import a patch
1930 """import a patch
1931
1931
1932 The patch is inserted into the series after the last applied
1932 The patch is inserted into the series after the last applied
1933 patch. If no patches have been applied, qimport prepends the patch
1933 patch. If no patches have been applied, qimport prepends the patch
1934 to the series.
1934 to the series.
1935
1935
1936 The patch will have the same name as its source file unless you
1936 The patch will have the same name as its source file unless you
1937 give it a new one with -n/--name.
1937 give it a new one with -n/--name.
1938
1938
1939 You can register an existing patch inside the patch directory with
1939 You can register an existing patch inside the patch directory with
1940 the -e/--existing flag.
1940 the -e/--existing flag.
1941
1941
1942 With -f/--force, an existing patch of the same name will be
1942 With -f/--force, an existing patch of the same name will be
1943 overwritten.
1943 overwritten.
1944
1944
1945 An existing changeset may be placed under mq control with -r/--rev
1945 An existing changeset may be placed under mq control with -r/--rev
1946 (e.g. qimport --rev tip -n patch will place tip under mq control).
1946 (e.g. qimport --rev tip -n patch will place tip under mq control).
1947 With -g/--git, patches imported with --rev will use the git diff
1947 With -g/--git, patches imported with --rev will use the git diff
1948 format. See the diffs help topic for information on why this is
1948 format. See the diffs help topic for information on why this is
1949 important for preserving rename/copy information and permission
1949 important for preserving rename/copy information and permission
1950 changes. Use :hg:`qfinish` to remove changesets from mq control.
1950 changes. Use :hg:`qfinish` to remove changesets from mq control.
1951
1951
1952 To import a patch from standard input, pass - as the patch file.
1952 To import a patch from standard input, pass - as the patch file.
1953 When importing from standard input, a patch name must be specified
1953 When importing from standard input, a patch name must be specified
1954 using the --name flag.
1954 using the --name flag.
1955
1955
1956 To import an existing patch while renaming it::
1956 To import an existing patch while renaming it::
1957
1957
1958 hg qimport -e existing-patch -n new-name
1958 hg qimport -e existing-patch -n new-name
1959
1959
1960 Returns 0 if import succeeded.
1960 Returns 0 if import succeeded.
1961 """
1961 """
1962 q = repo.mq
1962 q = repo.mq
1963 try:
1963 try:
1964 q.qimport(repo, filename, patchname=opts.get('name'),
1964 q.qimport(repo, filename, patchname=opts.get('name'),
1965 existing=opts.get('existing'), force=opts.get('force'),
1965 existing=opts.get('existing'), force=opts.get('force'),
1966 rev=opts.get('rev'), git=opts.get('git'))
1966 rev=opts.get('rev'), git=opts.get('git'))
1967 finally:
1967 finally:
1968 q.savedirty()
1968 q.savedirty()
1969
1969
1970 if opts.get('push') and not opts.get('rev'):
1970 if opts.get('push') and not opts.get('rev'):
1971 return q.push(repo, None)
1971 return q.push(repo, None)
1972 return 0
1972 return 0
1973
1973
1974 def qinit(ui, repo, create):
1974 def qinit(ui, repo, create):
1975 """initialize a new queue repository
1975 """initialize a new queue repository
1976
1976
1977 This command also creates a series file for ordering patches, and
1977 This command also creates a series file for ordering patches, and
1978 an mq-specific .hgignore file in the queue repository, to exclude
1978 an mq-specific .hgignore file in the queue repository, to exclude
1979 the status and guards files (these contain mostly transient state).
1979 the status and guards files (these contain mostly transient state).
1980
1980
1981 Returns 0 if initialization succeeded."""
1981 Returns 0 if initialization succeeded."""
1982 q = repo.mq
1982 q = repo.mq
1983 r = q.init(repo, create)
1983 r = q.init(repo, create)
1984 q.savedirty()
1984 q.savedirty()
1985 if r:
1985 if r:
1986 if not os.path.exists(r.wjoin('.hgignore')):
1986 if not os.path.exists(r.wjoin('.hgignore')):
1987 fp = r.wopener('.hgignore', 'w')
1987 fp = r.wopener('.hgignore', 'w')
1988 fp.write('^\\.hg\n')
1988 fp.write('^\\.hg\n')
1989 fp.write('^\\.mq\n')
1989 fp.write('^\\.mq\n')
1990 fp.write('syntax: glob\n')
1990 fp.write('syntax: glob\n')
1991 fp.write('status\n')
1991 fp.write('status\n')
1992 fp.write('guards\n')
1992 fp.write('guards\n')
1993 fp.close()
1993 fp.close()
1994 if not os.path.exists(r.wjoin('series')):
1994 if not os.path.exists(r.wjoin('series')):
1995 r.wopener('series', 'w').close()
1995 r.wopener('series', 'w').close()
1996 r[None].add(['.hgignore', 'series'])
1996 r[None].add(['.hgignore', 'series'])
1997 commands.add(ui, r)
1997 commands.add(ui, r)
1998 return 0
1998 return 0
1999
1999
2000 @command("^qinit",
2000 @command("^qinit",
2001 [('c', 'create-repo', None, _('create queue repository'))],
2001 [('c', 'create-repo', None, _('create queue repository'))],
2002 _('hg qinit [-c]'))
2002 _('hg qinit [-c]'))
2003 def init(ui, repo, **opts):
2003 def init(ui, repo, **opts):
2004 """init a new queue repository (DEPRECATED)
2004 """init a new queue repository (DEPRECATED)
2005
2005
2006 The queue repository is unversioned by default. If
2006 The queue repository is unversioned by default. If
2007 -c/--create-repo is specified, qinit will create a separate nested
2007 -c/--create-repo is specified, qinit will create a separate nested
2008 repository for patches (qinit -c may also be run later to convert
2008 repository for patches (qinit -c may also be run later to convert
2009 an unversioned patch repository into a versioned one). You can use
2009 an unversioned patch repository into a versioned one). You can use
2010 qcommit to commit changes to this queue repository.
2010 qcommit to commit changes to this queue repository.
2011
2011
2012 This command is deprecated. Without -c, it's implied by other relevant
2012 This command is deprecated. Without -c, it's implied by other relevant
2013 commands. With -c, use :hg:`init --mq` instead."""
2013 commands. With -c, use :hg:`init --mq` instead."""
2014 return qinit(ui, repo, create=opts.get('create_repo'))
2014 return qinit(ui, repo, create=opts.get('create_repo'))
2015
2015
2016 @command("qclone",
2016 @command("qclone",
2017 [('', 'pull', None, _('use pull protocol to copy metadata')),
2017 [('', 'pull', None, _('use pull protocol to copy metadata')),
2018 ('U', 'noupdate', None, _('do not update the new working directories')),
2018 ('U', 'noupdate', None, _('do not update the new working directories')),
2019 ('', 'uncompressed', None,
2019 ('', 'uncompressed', None,
2020 _('use uncompressed transfer (fast over LAN)')),
2020 _('use uncompressed transfer (fast over LAN)')),
2021 ('p', 'patches', '',
2021 ('p', 'patches', '',
2022 _('location of source patch repository'), _('REPO')),
2022 _('location of source patch repository'), _('REPO')),
2023 ] + commands.remoteopts,
2023 ] + commands.remoteopts,
2024 _('hg qclone [OPTION]... SOURCE [DEST]'))
2024 _('hg qclone [OPTION]... SOURCE [DEST]'))
2025 def clone(ui, source, dest=None, **opts):
2025 def clone(ui, source, dest=None, **opts):
2026 '''clone main and patch repository at same time
2026 '''clone main and patch repository at same time
2027
2027
2028 If source is local, destination will have no patches applied. If
2028 If source is local, destination will have no patches applied. If
2029 source is remote, this command can not check if patches are
2029 source is remote, this command can not check if patches are
2030 applied in source, so cannot guarantee that patches are not
2030 applied in source, so cannot guarantee that patches are not
2031 applied in destination. If you clone remote repository, be sure
2031 applied in destination. If you clone remote repository, be sure
2032 before that it has no patches applied.
2032 before that it has no patches applied.
2033
2033
2034 Source patch repository is looked for in <src>/.hg/patches by
2034 Source patch repository is looked for in <src>/.hg/patches by
2035 default. Use -p <url> to change.
2035 default. Use -p <url> to change.
2036
2036
2037 The patch directory must be a nested Mercurial repository, as
2037 The patch directory must be a nested Mercurial repository, as
2038 would be created by :hg:`init --mq`.
2038 would be created by :hg:`init --mq`.
2039
2039
2040 Return 0 on success.
2040 Return 0 on success.
2041 '''
2041 '''
2042 def patchdir(repo):
2042 def patchdir(repo):
2043 url = repo.url()
2043 url = repo.url()
2044 if url.endswith('/'):
2044 if url.endswith('/'):
2045 url = url[:-1]
2045 url = url[:-1]
2046 return url + '/.hg/patches'
2046 return url + '/.hg/patches'
2047 if dest is None:
2047 if dest is None:
2048 dest = hg.defaultdest(source)
2048 dest = hg.defaultdest(source)
2049 sr = hg.repository(hg.remoteui(ui, opts), ui.expandpath(source))
2049 sr = hg.repository(hg.remoteui(ui, opts), ui.expandpath(source))
2050 if opts.get('patches'):
2050 if opts.get('patches'):
2051 patchespath = ui.expandpath(opts.get('patches'))
2051 patchespath = ui.expandpath(opts.get('patches'))
2052 else:
2052 else:
2053 patchespath = patchdir(sr)
2053 patchespath = patchdir(sr)
2054 try:
2054 try:
2055 hg.repository(ui, patchespath)
2055 hg.repository(ui, patchespath)
2056 except error.RepoError:
2056 except error.RepoError:
2057 raise util.Abort(_('versioned patch repository not found'
2057 raise util.Abort(_('versioned patch repository not found'
2058 ' (see init --mq)'))
2058 ' (see init --mq)'))
2059 qbase, destrev = None, None
2059 qbase, destrev = None, None
2060 if sr.local():
2060 if sr.local():
2061 if sr.mq.applied:
2061 if sr.mq.applied:
2062 qbase = sr.mq.applied[0].node
2062 qbase = sr.mq.applied[0].node
2063 if not hg.islocal(dest):
2063 if not hg.islocal(dest):
2064 heads = set(sr.heads())
2064 heads = set(sr.heads())
2065 destrev = list(heads.difference(sr.heads(qbase)))
2065 destrev = list(heads.difference(sr.heads(qbase)))
2066 destrev.append(sr.changelog.parents(qbase)[0])
2066 destrev.append(sr.changelog.parents(qbase)[0])
2067 elif sr.capable('lookup'):
2067 elif sr.capable('lookup'):
2068 try:
2068 try:
2069 qbase = sr.lookup('qbase')
2069 qbase = sr.lookup('qbase')
2070 except error.RepoError:
2070 except error.RepoError:
2071 pass
2071 pass
2072 ui.note(_('cloning main repository\n'))
2072 ui.note(_('cloning main repository\n'))
2073 sr, dr = hg.clone(ui, opts, sr.url(), dest,
2073 sr, dr = hg.clone(ui, opts, sr.url(), dest,
2074 pull=opts.get('pull'),
2074 pull=opts.get('pull'),
2075 rev=destrev,
2075 rev=destrev,
2076 update=False,
2076 update=False,
2077 stream=opts.get('uncompressed'))
2077 stream=opts.get('uncompressed'))
2078 ui.note(_('cloning patch repository\n'))
2078 ui.note(_('cloning patch repository\n'))
2079 hg.clone(ui, opts, opts.get('patches') or patchdir(sr), patchdir(dr),
2079 hg.clone(ui, opts, opts.get('patches') or patchdir(sr), patchdir(dr),
2080 pull=opts.get('pull'), update=not opts.get('noupdate'),
2080 pull=opts.get('pull'), update=not opts.get('noupdate'),
2081 stream=opts.get('uncompressed'))
2081 stream=opts.get('uncompressed'))
2082 if dr.local():
2082 if dr.local():
2083 if qbase:
2083 if qbase:
2084 ui.note(_('stripping applied patches from destination '
2084 ui.note(_('stripping applied patches from destination '
2085 'repository\n'))
2085 'repository\n'))
2086 dr.mq.strip(dr, [qbase], update=False, backup=None)
2086 dr.mq.strip(dr, [qbase], update=False, backup=None)
2087 if not opts.get('noupdate'):
2087 if not opts.get('noupdate'):
2088 ui.note(_('updating destination repository\n'))
2088 ui.note(_('updating destination repository\n'))
2089 hg.update(dr, dr.changelog.tip())
2089 hg.update(dr, dr.changelog.tip())
2090
2090
2091 @command("qcommit|qci",
2091 @command("qcommit|qci",
2092 commands.table["^commit|ci"][1],
2092 commands.table["^commit|ci"][1],
2093 _('hg qcommit [OPTION]... [FILE]...'))
2093 _('hg qcommit [OPTION]... [FILE]...'))
2094 def commit(ui, repo, *pats, **opts):
2094 def commit(ui, repo, *pats, **opts):
2095 """commit changes in the queue repository (DEPRECATED)
2095 """commit changes in the queue repository (DEPRECATED)
2096
2096
2097 This command is deprecated; use :hg:`commit --mq` instead."""
2097 This command is deprecated; use :hg:`commit --mq` instead."""
2098 q = repo.mq
2098 q = repo.mq
2099 r = q.qrepo()
2099 r = q.qrepo()
2100 if not r:
2100 if not r:
2101 raise util.Abort('no queue repository')
2101 raise util.Abort('no queue repository')
2102 commands.commit(r.ui, r, *pats, **opts)
2102 commands.commit(r.ui, r, *pats, **opts)
2103
2103
2104 @command("qseries",
2104 @command("qseries",
2105 [('m', 'missing', None, _('print patches not in series')),
2105 [('m', 'missing', None, _('print patches not in series')),
2106 ] + seriesopts,
2106 ] + seriesopts,
2107 _('hg qseries [-ms]'))
2107 _('hg qseries [-ms]'))
2108 def series(ui, repo, **opts):
2108 def series(ui, repo, **opts):
2109 """print the entire series file
2109 """print the entire series file
2110
2110
2111 Returns 0 on success."""
2111 Returns 0 on success."""
2112 repo.mq.qseries(repo, missing=opts.get('missing'), summary=opts.get('summary'))
2112 repo.mq.qseries(repo, missing=opts.get('missing'), summary=opts.get('summary'))
2113 return 0
2113 return 0
2114
2114
2115 @command("qtop", seriesopts, _('hg qtop [-s]'))
2115 @command("qtop", seriesopts, _('hg qtop [-s]'))
2116 def top(ui, repo, **opts):
2116 def top(ui, repo, **opts):
2117 """print the name of the current patch
2117 """print the name of the current patch
2118
2118
2119 Returns 0 on success."""
2119 Returns 0 on success."""
2120 q = repo.mq
2120 q = repo.mq
2121 t = q.applied and q.seriesend(True) or 0
2121 t = q.applied and q.seriesend(True) or 0
2122 if t:
2122 if t:
2123 q.qseries(repo, start=t - 1, length=1, status='A',
2123 q.qseries(repo, start=t - 1, length=1, status='A',
2124 summary=opts.get('summary'))
2124 summary=opts.get('summary'))
2125 else:
2125 else:
2126 ui.write(_("no patches applied\n"))
2126 ui.write(_("no patches applied\n"))
2127 return 1
2127 return 1
2128
2128
2129 @command("qnext", seriesopts, _('hg qnext [-s]'))
2129 @command("qnext", seriesopts, _('hg qnext [-s]'))
2130 def next(ui, repo, **opts):
2130 def next(ui, repo, **opts):
2131 """print the name of the next patch
2131 """print the name of the next patch
2132
2132
2133 Returns 0 on success."""
2133 Returns 0 on success."""
2134 q = repo.mq
2134 q = repo.mq
2135 end = q.seriesend()
2135 end = q.seriesend()
2136 if end == len(q.series):
2136 if end == len(q.series):
2137 ui.write(_("all patches applied\n"))
2137 ui.write(_("all patches applied\n"))
2138 return 1
2138 return 1
2139 q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
2139 q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
2140
2140
2141 @command("qprev", seriesopts, _('hg qprev [-s]'))
2141 @command("qprev", seriesopts, _('hg qprev [-s]'))
2142 def prev(ui, repo, **opts):
2142 def prev(ui, repo, **opts):
2143 """print the name of the previous patch
2143 """print the name of the previous patch
2144
2144
2145 Returns 0 on success."""
2145 Returns 0 on success."""
2146 q = repo.mq
2146 q = repo.mq
2147 l = len(q.applied)
2147 l = len(q.applied)
2148 if l == 1:
2148 if l == 1:
2149 ui.write(_("only one patch applied\n"))
2149 ui.write(_("only one patch applied\n"))
2150 return 1
2150 return 1
2151 if not l:
2151 if not l:
2152 ui.write(_("no patches applied\n"))
2152 ui.write(_("no patches applied\n"))
2153 return 1
2153 return 1
2154 q.qseries(repo, start=l - 2, length=1, status='A',
2154 q.qseries(repo, start=l - 2, length=1, status='A',
2155 summary=opts.get('summary'))
2155 summary=opts.get('summary'))
2156
2156
2157 def setupheaderopts(ui, opts):
2157 def setupheaderopts(ui, opts):
2158 if not opts.get('user') and opts.get('currentuser'):
2158 if not opts.get('user') and opts.get('currentuser'):
2159 opts['user'] = ui.username()
2159 opts['user'] = ui.username()
2160 if not opts.get('date') and opts.get('currentdate'):
2160 if not opts.get('date') and opts.get('currentdate'):
2161 opts['date'] = "%d %d" % util.makedate()
2161 opts['date'] = "%d %d" % util.makedate()
2162
2162
2163 @command("^qnew",
2163 @command("^qnew",
2164 [('e', 'edit', None, _('edit commit message')),
2164 [('e', 'edit', None, _('edit commit message')),
2165 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2165 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2166 ('g', 'git', None, _('use git extended diff format')),
2166 ('g', 'git', None, _('use git extended diff format')),
2167 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2167 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2168 ('u', 'user', '',
2168 ('u', 'user', '',
2169 _('add "From: <USER>" to patch'), _('USER')),
2169 _('add "From: <USER>" to patch'), _('USER')),
2170 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2170 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2171 ('d', 'date', '',
2171 ('d', 'date', '',
2172 _('add "Date: <DATE>" to patch'), _('DATE'))
2172 _('add "Date: <DATE>" to patch'), _('DATE'))
2173 ] + commands.walkopts + commands.commitopts,
2173 ] + commands.walkopts + commands.commitopts,
2174 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'))
2174 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'))
2175 def new(ui, repo, patch, *args, **opts):
2175 def new(ui, repo, patch, *args, **opts):
2176 """create a new patch
2176 """create a new patch
2177
2177
2178 qnew creates a new patch on top of the currently-applied patch (if
2178 qnew creates a new patch on top of the currently-applied patch (if
2179 any). The patch will be initialized with any outstanding changes
2179 any). The patch will be initialized with any outstanding changes
2180 in the working directory. You may also use -I/--include,
2180 in the working directory. You may also use -I/--include,
2181 -X/--exclude, and/or a list of files after the patch name to add
2181 -X/--exclude, and/or a list of files after the patch name to add
2182 only changes to matching files to the new patch, leaving the rest
2182 only changes to matching files to the new patch, leaving the rest
2183 as uncommitted modifications.
2183 as uncommitted modifications.
2184
2184
2185 -u/--user and -d/--date can be used to set the (given) user and
2185 -u/--user and -d/--date can be used to set the (given) user and
2186 date, respectively. -U/--currentuser and -D/--currentdate set user
2186 date, respectively. -U/--currentuser and -D/--currentdate set user
2187 to current user and date to current date.
2187 to current user and date to current date.
2188
2188
2189 -e/--edit, -m/--message or -l/--logfile set the patch header as
2189 -e/--edit, -m/--message or -l/--logfile set the patch header as
2190 well as the commit message. If none is specified, the header is
2190 well as the commit message. If none is specified, the header is
2191 empty and the commit message is '[mq]: PATCH'.
2191 empty and the commit message is '[mq]: PATCH'.
2192
2192
2193 Use the -g/--git option to keep the patch in the git extended diff
2193 Use the -g/--git option to keep the patch in the git extended diff
2194 format. Read the diffs help topic for more information on why this
2194 format. Read the diffs help topic for more information on why this
2195 is important for preserving permission changes and copy/rename
2195 is important for preserving permission changes and copy/rename
2196 information.
2196 information.
2197
2197
2198 Returns 0 on successful creation of a new patch.
2198 Returns 0 on successful creation of a new patch.
2199 """
2199 """
2200 msg = cmdutil.logmessage(ui, opts)
2200 msg = cmdutil.logmessage(ui, opts)
2201 def getmsg():
2201 def getmsg():
2202 return ui.edit(msg, opts.get('user') or ui.username())
2202 return ui.edit(msg, opts.get('user') or ui.username())
2203 q = repo.mq
2203 q = repo.mq
2204 opts['msg'] = msg
2204 opts['msg'] = msg
2205 if opts.get('edit'):
2205 if opts.get('edit'):
2206 opts['msg'] = getmsg
2206 opts['msg'] = getmsg
2207 else:
2207 else:
2208 opts['msg'] = msg
2208 opts['msg'] = msg
2209 setupheaderopts(ui, opts)
2209 setupheaderopts(ui, opts)
2210 q.new(repo, patch, *args, **opts)
2210 q.new(repo, patch, *args, **opts)
2211 q.savedirty()
2211 q.savedirty()
2212 return 0
2212 return 0
2213
2213
2214 @command("^qrefresh",
2214 @command("^qrefresh",
2215 [('e', 'edit', None, _('edit commit message')),
2215 [('e', 'edit', None, _('edit commit message')),
2216 ('g', 'git', None, _('use git extended diff format')),
2216 ('g', 'git', None, _('use git extended diff format')),
2217 ('s', 'short', None,
2217 ('s', 'short', None,
2218 _('refresh only files already in the patch and specified files')),
2218 _('refresh only files already in the patch and specified files')),
2219 ('U', 'currentuser', None,
2219 ('U', 'currentuser', None,
2220 _('add/update author field in patch with current user')),
2220 _('add/update author field in patch with current user')),
2221 ('u', 'user', '',
2221 ('u', 'user', '',
2222 _('add/update author field in patch with given user'), _('USER')),
2222 _('add/update author field in patch with given user'), _('USER')),
2223 ('D', 'currentdate', None,
2223 ('D', 'currentdate', None,
2224 _('add/update date field in patch with current date')),
2224 _('add/update date field in patch with current date')),
2225 ('d', 'date', '',
2225 ('d', 'date', '',
2226 _('add/update date field in patch with given date'), _('DATE'))
2226 _('add/update date field in patch with given date'), _('DATE'))
2227 ] + commands.walkopts + commands.commitopts,
2227 ] + commands.walkopts + commands.commitopts,
2228 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'))
2228 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'))
2229 def refresh(ui, repo, *pats, **opts):
2229 def refresh(ui, repo, *pats, **opts):
2230 """update the current patch
2230 """update the current patch
2231
2231
2232 If any file patterns are provided, the refreshed patch will
2232 If any file patterns are provided, the refreshed patch will
2233 contain only the modifications that match those patterns; the
2233 contain only the modifications that match those patterns; the
2234 remaining modifications will remain in the working directory.
2234 remaining modifications will remain in the working directory.
2235
2235
2236 If -s/--short is specified, files currently included in the patch
2236 If -s/--short is specified, files currently included in the patch
2237 will be refreshed just like matched files and remain in the patch.
2237 will be refreshed just like matched files and remain in the patch.
2238
2238
2239 If -e/--edit is specified, Mercurial will start your configured editor for
2239 If -e/--edit is specified, Mercurial will start your configured editor for
2240 you to enter a message. In case qrefresh fails, you will find a backup of
2240 you to enter a message. In case qrefresh fails, you will find a backup of
2241 your message in ``.hg/last-message.txt``.
2241 your message in ``.hg/last-message.txt``.
2242
2242
2243 hg add/remove/copy/rename work as usual, though you might want to
2243 hg add/remove/copy/rename work as usual, though you might want to
2244 use git-style patches (-g/--git or [diff] git=1) to track copies
2244 use git-style patches (-g/--git or [diff] git=1) to track copies
2245 and renames. See the diffs help topic for more information on the
2245 and renames. See the diffs help topic for more information on the
2246 git diff format.
2246 git diff format.
2247
2247
2248 Returns 0 on success.
2248 Returns 0 on success.
2249 """
2249 """
2250 q = repo.mq
2250 q = repo.mq
2251 message = cmdutil.logmessage(ui, opts)
2251 message = cmdutil.logmessage(ui, opts)
2252 if opts.get('edit'):
2252 if opts.get('edit'):
2253 if not q.applied:
2253 if not q.applied:
2254 ui.write(_("no patches applied\n"))
2254 ui.write(_("no patches applied\n"))
2255 return 1
2255 return 1
2256 if message:
2256 if message:
2257 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2257 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2258 patch = q.applied[-1].name
2258 patch = q.applied[-1].name
2259 ph = patchheader(q.join(patch), q.plainmode)
2259 ph = patchheader(q.join(patch), q.plainmode)
2260 message = ui.edit('\n'.join(ph.message), ph.user or ui.username())
2260 message = ui.edit('\n'.join(ph.message), ph.user or ui.username())
2261 # We don't want to lose the patch message if qrefresh fails (issue2062)
2261 # We don't want to lose the patch message if qrefresh fails (issue2062)
2262 repo.savecommitmessage(message)
2262 repo.savecommitmessage(message)
2263 setupheaderopts(ui, opts)
2263 setupheaderopts(ui, opts)
2264 wlock = repo.wlock()
2264 wlock = repo.wlock()
2265 try:
2265 try:
2266 ret = q.refresh(repo, pats, msg=message, **opts)
2266 ret = q.refresh(repo, pats, msg=message, **opts)
2267 q.savedirty()
2267 q.savedirty()
2268 return ret
2268 return ret
2269 finally:
2269 finally:
2270 wlock.release()
2270 wlock.release()
2271
2271
2272 @command("^qdiff",
2272 @command("^qdiff",
2273 commands.diffopts + commands.diffopts2 + commands.walkopts,
2273 commands.diffopts + commands.diffopts2 + commands.walkopts,
2274 _('hg qdiff [OPTION]... [FILE]...'))
2274 _('hg qdiff [OPTION]... [FILE]...'))
2275 def diff(ui, repo, *pats, **opts):
2275 def diff(ui, repo, *pats, **opts):
2276 """diff of the current patch and subsequent modifications
2276 """diff of the current patch and subsequent modifications
2277
2277
2278 Shows a diff which includes the current patch as well as any
2278 Shows a diff which includes the current patch as well as any
2279 changes which have been made in the working directory since the
2279 changes which have been made in the working directory since the
2280 last refresh (thus showing what the current patch would become
2280 last refresh (thus showing what the current patch would become
2281 after a qrefresh).
2281 after a qrefresh).
2282
2282
2283 Use :hg:`diff` if you only want to see the changes made since the
2283 Use :hg:`diff` if you only want to see the changes made since the
2284 last qrefresh, or :hg:`export qtip` if you want to see changes
2284 last qrefresh, or :hg:`export qtip` if you want to see changes
2285 made by the current patch without including changes made since the
2285 made by the current patch without including changes made since the
2286 qrefresh.
2286 qrefresh.
2287
2287
2288 Returns 0 on success.
2288 Returns 0 on success.
2289 """
2289 """
2290 repo.mq.diff(repo, pats, opts)
2290 repo.mq.diff(repo, pats, opts)
2291 return 0
2291 return 0
2292
2292
2293 @command('qfold',
2293 @command('qfold',
2294 [('e', 'edit', None, _('edit patch header')),
2294 [('e', 'edit', None, _('edit patch header')),
2295 ('k', 'keep', None, _('keep folded patch files')),
2295 ('k', 'keep', None, _('keep folded patch files')),
2296 ] + commands.commitopts,
2296 ] + commands.commitopts,
2297 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'))
2297 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'))
2298 def fold(ui, repo, *files, **opts):
2298 def fold(ui, repo, *files, **opts):
2299 """fold the named patches into the current patch
2299 """fold the named patches into the current patch
2300
2300
2301 Patches must not yet be applied. Each patch will be successively
2301 Patches must not yet be applied. Each patch will be successively
2302 applied to the current patch in the order given. If all the
2302 applied to the current patch in the order given. If all the
2303 patches apply successfully, the current patch will be refreshed
2303 patches apply successfully, the current patch will be refreshed
2304 with the new cumulative patch, and the folded patches will be
2304 with the new cumulative patch, and the folded patches will be
2305 deleted. With -k/--keep, the folded patch files will not be
2305 deleted. With -k/--keep, the folded patch files will not be
2306 removed afterwards.
2306 removed afterwards.
2307
2307
2308 The header for each folded patch will be concatenated with the
2308 The header for each folded patch will be concatenated with the
2309 current patch header, separated by a line of ``* * *``.
2309 current patch header, separated by a line of ``* * *``.
2310
2310
2311 Returns 0 on success."""
2311 Returns 0 on success."""
2312
2312
2313 q = repo.mq
2313 q = repo.mq
2314
2314
2315 if not files:
2315 if not files:
2316 raise util.Abort(_('qfold requires at least one patch name'))
2316 raise util.Abort(_('qfold requires at least one patch name'))
2317 if not q.checktoppatch(repo)[0]:
2317 if not q.checktoppatch(repo)[0]:
2318 raise util.Abort(_('no patches applied'))
2318 raise util.Abort(_('no patches applied'))
2319 q.checklocalchanges(repo)
2319 q.checklocalchanges(repo)
2320
2320
2321 message = cmdutil.logmessage(ui, opts)
2321 message = cmdutil.logmessage(ui, opts)
2322 if opts.get('edit'):
2322 if opts.get('edit'):
2323 if message:
2323 if message:
2324 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2324 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2325
2325
2326 parent = q.lookup('qtip')
2326 parent = q.lookup('qtip')
2327 patches = []
2327 patches = []
2328 messages = []
2328 messages = []
2329 for f in files:
2329 for f in files:
2330 p = q.lookup(f)
2330 p = q.lookup(f)
2331 if p in patches or p == parent:
2331 if p in patches or p == parent:
2332 ui.warn(_('Skipping already folded patch %s\n') % p)
2332 ui.warn(_('Skipping already folded patch %s\n') % p)
2333 if q.isapplied(p):
2333 if q.isapplied(p):
2334 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
2334 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
2335 patches.append(p)
2335 patches.append(p)
2336
2336
2337 for p in patches:
2337 for p in patches:
2338 if not message:
2338 if not message:
2339 ph = patchheader(q.join(p), q.plainmode)
2339 ph = patchheader(q.join(p), q.plainmode)
2340 if ph.message:
2340 if ph.message:
2341 messages.append(ph.message)
2341 messages.append(ph.message)
2342 pf = q.join(p)
2342 pf = q.join(p)
2343 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2343 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2344 if not patchsuccess:
2344 if not patchsuccess:
2345 raise util.Abort(_('error folding patch %s') % p)
2345 raise util.Abort(_('error folding patch %s') % p)
2346
2346
2347 if not message:
2347 if not message:
2348 ph = patchheader(q.join(parent), q.plainmode)
2348 ph = patchheader(q.join(parent), q.plainmode)
2349 message, user = ph.message, ph.user
2349 message, user = ph.message, ph.user
2350 for msg in messages:
2350 for msg in messages:
2351 message.append('* * *')
2351 message.append('* * *')
2352 message.extend(msg)
2352 message.extend(msg)
2353 message = '\n'.join(message)
2353 message = '\n'.join(message)
2354
2354
2355 if opts.get('edit'):
2355 if opts.get('edit'):
2356 message = ui.edit(message, user or ui.username())
2356 message = ui.edit(message, user or ui.username())
2357
2357
2358 diffopts = q.patchopts(q.diffopts(), *patches)
2358 diffopts = q.patchopts(q.diffopts(), *patches)
2359 wlock = repo.wlock()
2359 wlock = repo.wlock()
2360 try:
2360 try:
2361 q.refresh(repo, msg=message, git=diffopts.git)
2361 q.refresh(repo, msg=message, git=diffopts.git)
2362 q.delete(repo, patches, opts)
2362 q.delete(repo, patches, opts)
2363 q.savedirty()
2363 q.savedirty()
2364 finally:
2364 finally:
2365 wlock.release()
2365 wlock.release()
2366
2366
2367 @command("qgoto",
2367 @command("qgoto",
2368 [('f', 'force', None, _('overwrite any local changes'))],
2368 [('f', 'force', None, _('overwrite any local changes'))],
2369 _('hg qgoto [OPTION]... PATCH'))
2369 _('hg qgoto [OPTION]... PATCH'))
2370 def goto(ui, repo, patch, **opts):
2370 def goto(ui, repo, patch, **opts):
2371 '''push or pop patches until named patch is at top of stack
2371 '''push or pop patches until named patch is at top of stack
2372
2372
2373 Returns 0 on success.'''
2373 Returns 0 on success.'''
2374 q = repo.mq
2374 q = repo.mq
2375 patch = q.lookup(patch)
2375 patch = q.lookup(patch)
2376 if q.isapplied(patch):
2376 if q.isapplied(patch):
2377 ret = q.pop(repo, patch, force=opts.get('force'))
2377 ret = q.pop(repo, patch, force=opts.get('force'))
2378 else:
2378 else:
2379 ret = q.push(repo, patch, force=opts.get('force'))
2379 ret = q.push(repo, patch, force=opts.get('force'))
2380 q.savedirty()
2380 q.savedirty()
2381 return ret
2381 return ret
2382
2382
2383 @command("qguard",
2383 @command("qguard",
2384 [('l', 'list', None, _('list all patches and guards')),
2384 [('l', 'list', None, _('list all patches and guards')),
2385 ('n', 'none', None, _('drop all guards'))],
2385 ('n', 'none', None, _('drop all guards'))],
2386 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'))
2386 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'))
2387 def guard(ui, repo, *args, **opts):
2387 def guard(ui, repo, *args, **opts):
2388 '''set or print guards for a patch
2388 '''set or print guards for a patch
2389
2389
2390 Guards control whether a patch can be pushed. A patch with no
2390 Guards control whether a patch can be pushed. A patch with no
2391 guards is always pushed. A patch with a positive guard ("+foo") is
2391 guards is always pushed. A patch with a positive guard ("+foo") is
2392 pushed only if the :hg:`qselect` command has activated it. A patch with
2392 pushed only if the :hg:`qselect` command has activated it. A patch with
2393 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
2393 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
2394 has activated it.
2394 has activated it.
2395
2395
2396 With no arguments, print the currently active guards.
2396 With no arguments, print the currently active guards.
2397 With arguments, set guards for the named patch.
2397 With arguments, set guards for the named patch.
2398
2398
2399 .. note::
2399 .. note::
2400 Specifying negative guards now requires '--'.
2400 Specifying negative guards now requires '--'.
2401
2401
2402 To set guards on another patch::
2402 To set guards on another patch::
2403
2403
2404 hg qguard other.patch -- +2.6.17 -stable
2404 hg qguard other.patch -- +2.6.17 -stable
2405
2405
2406 Returns 0 on success.
2406 Returns 0 on success.
2407 '''
2407 '''
2408 def status(idx):
2408 def status(idx):
2409 guards = q.seriesguards[idx] or ['unguarded']
2409 guards = q.seriesguards[idx] or ['unguarded']
2410 if q.series[idx] in applied:
2410 if q.series[idx] in applied:
2411 state = 'applied'
2411 state = 'applied'
2412 elif q.pushable(idx)[0]:
2412 elif q.pushable(idx)[0]:
2413 state = 'unapplied'
2413 state = 'unapplied'
2414 else:
2414 else:
2415 state = 'guarded'
2415 state = 'guarded'
2416 label = 'qguard.patch qguard.%s qseries.%s' % (state, state)
2416 label = 'qguard.patch qguard.%s qseries.%s' % (state, state)
2417 ui.write('%s: ' % ui.label(q.series[idx], label))
2417 ui.write('%s: ' % ui.label(q.series[idx], label))
2418
2418
2419 for i, guard in enumerate(guards):
2419 for i, guard in enumerate(guards):
2420 if guard.startswith('+'):
2420 if guard.startswith('+'):
2421 ui.write(guard, label='qguard.positive')
2421 ui.write(guard, label='qguard.positive')
2422 elif guard.startswith('-'):
2422 elif guard.startswith('-'):
2423 ui.write(guard, label='qguard.negative')
2423 ui.write(guard, label='qguard.negative')
2424 else:
2424 else:
2425 ui.write(guard, label='qguard.unguarded')
2425 ui.write(guard, label='qguard.unguarded')
2426 if i != len(guards) - 1:
2426 if i != len(guards) - 1:
2427 ui.write(' ')
2427 ui.write(' ')
2428 ui.write('\n')
2428 ui.write('\n')
2429 q = repo.mq
2429 q = repo.mq
2430 applied = set(p.name for p in q.applied)
2430 applied = set(p.name for p in q.applied)
2431 patch = None
2431 patch = None
2432 args = list(args)
2432 args = list(args)
2433 if opts.get('list'):
2433 if opts.get('list'):
2434 if args or opts.get('none'):
2434 if args or opts.get('none'):
2435 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
2435 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
2436 for i in xrange(len(q.series)):
2436 for i in xrange(len(q.series)):
2437 status(i)
2437 status(i)
2438 return
2438 return
2439 if not args or args[0][0:1] in '-+':
2439 if not args or args[0][0:1] in '-+':
2440 if not q.applied:
2440 if not q.applied:
2441 raise util.Abort(_('no patches applied'))
2441 raise util.Abort(_('no patches applied'))
2442 patch = q.applied[-1].name
2442 patch = q.applied[-1].name
2443 if patch is None and args[0][0:1] not in '-+':
2443 if patch is None and args[0][0:1] not in '-+':
2444 patch = args.pop(0)
2444 patch = args.pop(0)
2445 if patch is None:
2445 if patch is None:
2446 raise util.Abort(_('no patch to work with'))
2446 raise util.Abort(_('no patch to work with'))
2447 if args or opts.get('none'):
2447 if args or opts.get('none'):
2448 idx = q.findseries(patch)
2448 idx = q.findseries(patch)
2449 if idx is None:
2449 if idx is None:
2450 raise util.Abort(_('no patch named %s') % patch)
2450 raise util.Abort(_('no patch named %s') % patch)
2451 q.setguards(idx, args)
2451 q.setguards(idx, args)
2452 q.savedirty()
2452 q.savedirty()
2453 else:
2453 else:
2454 status(q.series.index(q.lookup(patch)))
2454 status(q.series.index(q.lookup(patch)))
2455
2455
2456 @command("qheader", [], _('hg qheader [PATCH]'))
2456 @command("qheader", [], _('hg qheader [PATCH]'))
2457 def header(ui, repo, patch=None):
2457 def header(ui, repo, patch=None):
2458 """print the header of the topmost or specified patch
2458 """print the header of the topmost or specified patch
2459
2459
2460 Returns 0 on success."""
2460 Returns 0 on success."""
2461 q = repo.mq
2461 q = repo.mq
2462
2462
2463 if patch:
2463 if patch:
2464 patch = q.lookup(patch)
2464 patch = q.lookup(patch)
2465 else:
2465 else:
2466 if not q.applied:
2466 if not q.applied:
2467 ui.write(_('no patches applied\n'))
2467 ui.write(_('no patches applied\n'))
2468 return 1
2468 return 1
2469 patch = q.lookup('qtip')
2469 patch = q.lookup('qtip')
2470 ph = patchheader(q.join(patch), q.plainmode)
2470 ph = patchheader(q.join(patch), q.plainmode)
2471
2471
2472 ui.write('\n'.join(ph.message) + '\n')
2472 ui.write('\n'.join(ph.message) + '\n')
2473
2473
2474 def lastsavename(path):
2474 def lastsavename(path):
2475 (directory, base) = os.path.split(path)
2475 (directory, base) = os.path.split(path)
2476 names = os.listdir(directory)
2476 names = os.listdir(directory)
2477 namere = re.compile("%s.([0-9]+)" % base)
2477 namere = re.compile("%s.([0-9]+)" % base)
2478 maxindex = None
2478 maxindex = None
2479 maxname = None
2479 maxname = None
2480 for f in names:
2480 for f in names:
2481 m = namere.match(f)
2481 m = namere.match(f)
2482 if m:
2482 if m:
2483 index = int(m.group(1))
2483 index = int(m.group(1))
2484 if maxindex is None or index > maxindex:
2484 if maxindex is None or index > maxindex:
2485 maxindex = index
2485 maxindex = index
2486 maxname = f
2486 maxname = f
2487 if maxname:
2487 if maxname:
2488 return (os.path.join(directory, maxname), maxindex)
2488 return (os.path.join(directory, maxname), maxindex)
2489 return (None, None)
2489 return (None, None)
2490
2490
2491 def savename(path):
2491 def savename(path):
2492 (last, index) = lastsavename(path)
2492 (last, index) = lastsavename(path)
2493 if last is None:
2493 if last is None:
2494 index = 0
2494 index = 0
2495 newpath = path + ".%d" % (index + 1)
2495 newpath = path + ".%d" % (index + 1)
2496 return newpath
2496 return newpath
2497
2497
2498 @command("^qpush",
2498 @command("^qpush",
2499 [('f', 'force', None, _('apply on top of local changes')),
2499 [('f', 'force', None, _('apply on top of local changes')),
2500 ('e', 'exact', None, _('apply the target patch to its recorded parent')),
2500 ('e', 'exact', None, _('apply the target patch to its recorded parent')),
2501 ('l', 'list', None, _('list patch name in commit text')),
2501 ('l', 'list', None, _('list patch name in commit text')),
2502 ('a', 'all', None, _('apply all patches')),
2502 ('a', 'all', None, _('apply all patches')),
2503 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2503 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2504 ('n', 'name', '',
2504 ('n', 'name', '',
2505 _('merge queue name (DEPRECATED)'), _('NAME')),
2505 _('merge queue name (DEPRECATED)'), _('NAME')),
2506 ('', 'move', None, _('reorder patch series and apply only the patch'))],
2506 ('', 'move', None, _('reorder patch series and apply only the patch'))],
2507 _('hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'))
2507 _('hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'))
2508 def push(ui, repo, patch=None, **opts):
2508 def push(ui, repo, patch=None, **opts):
2509 """push the next patch onto the stack
2509 """push the next patch onto the stack
2510
2510
2511 When -f/--force is applied, all local changes in patched files
2511 When -f/--force is applied, all local changes in patched files
2512 will be lost.
2512 will be lost.
2513
2513
2514 Return 0 on success.
2514 Return 0 on success.
2515 """
2515 """
2516 q = repo.mq
2516 q = repo.mq
2517 mergeq = None
2517 mergeq = None
2518
2518
2519 if opts.get('merge'):
2519 if opts.get('merge'):
2520 if opts.get('name'):
2520 if opts.get('name'):
2521 newpath = repo.join(opts.get('name'))
2521 newpath = repo.join(opts.get('name'))
2522 else:
2522 else:
2523 newpath, i = lastsavename(q.path)
2523 newpath, i = lastsavename(q.path)
2524 if not newpath:
2524 if not newpath:
2525 ui.warn(_("no saved queues found, please use -n\n"))
2525 ui.warn(_("no saved queues found, please use -n\n"))
2526 return 1
2526 return 1
2527 mergeq = queue(ui, repo.join(""), newpath)
2527 mergeq = queue(ui, repo.join(""), newpath)
2528 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2528 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2529 ret = q.push(repo, patch, force=opts.get('force'), list=opts.get('list'),
2529 ret = q.push(repo, patch, force=opts.get('force'), list=opts.get('list'),
2530 mergeq=mergeq, all=opts.get('all'), move=opts.get('move'),
2530 mergeq=mergeq, all=opts.get('all'), move=opts.get('move'),
2531 exact=opts.get('exact'))
2531 exact=opts.get('exact'))
2532 return ret
2532 return ret
2533
2533
2534 @command("^qpop",
2534 @command("^qpop",
2535 [('a', 'all', None, _('pop all patches')),
2535 [('a', 'all', None, _('pop all patches')),
2536 ('n', 'name', '',
2536 ('n', 'name', '',
2537 _('queue name to pop (DEPRECATED)'), _('NAME')),
2537 _('queue name to pop (DEPRECATED)'), _('NAME')),
2538 ('f', 'force', None, _('forget any local changes to patched files'))],
2538 ('f', 'force', None, _('forget any local changes to patched files'))],
2539 _('hg qpop [-a] [-f] [PATCH | INDEX]'))
2539 _('hg qpop [-a] [-f] [PATCH | INDEX]'))
2540 def pop(ui, repo, patch=None, **opts):
2540 def pop(ui, repo, patch=None, **opts):
2541 """pop the current patch off the stack
2541 """pop the current patch off the stack
2542
2542
2543 By default, pops off the top of the patch stack. If given a patch
2543 By default, pops off the top of the patch stack. If given a patch
2544 name, keeps popping off patches until the named patch is at the
2544 name, keeps popping off patches until the named patch is at the
2545 top of the stack.
2545 top of the stack.
2546
2546
2547 Return 0 on success.
2547 Return 0 on success.
2548 """
2548 """
2549 localupdate = True
2549 localupdate = True
2550 if opts.get('name'):
2550 if opts.get('name'):
2551 q = queue(ui, repo.join(""), repo.join(opts.get('name')))
2551 q = queue(ui, repo.join(""), repo.join(opts.get('name')))
2552 ui.warn(_('using patch queue: %s\n') % q.path)
2552 ui.warn(_('using patch queue: %s\n') % q.path)
2553 localupdate = False
2553 localupdate = False
2554 else:
2554 else:
2555 q = repo.mq
2555 q = repo.mq
2556 ret = q.pop(repo, patch, force=opts.get('force'), update=localupdate,
2556 ret = q.pop(repo, patch, force=opts.get('force'), update=localupdate,
2557 all=opts.get('all'))
2557 all=opts.get('all'))
2558 q.savedirty()
2558 q.savedirty()
2559 return ret
2559 return ret
2560
2560
2561 @command("qrename|qmv", [], _('hg qrename PATCH1 [PATCH2]'))
2561 @command("qrename|qmv", [], _('hg qrename PATCH1 [PATCH2]'))
2562 def rename(ui, repo, patch, name=None, **opts):
2562 def rename(ui, repo, patch, name=None, **opts):
2563 """rename a patch
2563 """rename a patch
2564
2564
2565 With one argument, renames the current patch to PATCH1.
2565 With one argument, renames the current patch to PATCH1.
2566 With two arguments, renames PATCH1 to PATCH2.
2566 With two arguments, renames PATCH1 to PATCH2.
2567
2567
2568 Returns 0 on success."""
2568 Returns 0 on success."""
2569
2569
2570 q = repo.mq
2570 q = repo.mq
2571
2571
2572 if not name:
2572 if not name:
2573 name = patch
2573 name = patch
2574 patch = None
2574 patch = None
2575
2575
2576 if patch:
2576 if patch:
2577 patch = q.lookup(patch)
2577 patch = q.lookup(patch)
2578 else:
2578 else:
2579 if not q.applied:
2579 if not q.applied:
2580 ui.write(_('no patches applied\n'))
2580 ui.write(_('no patches applied\n'))
2581 return
2581 return
2582 patch = q.lookup('qtip')
2582 patch = q.lookup('qtip')
2583 absdest = q.join(name)
2583 absdest = q.join(name)
2584 if os.path.isdir(absdest):
2584 if os.path.isdir(absdest):
2585 name = normname(os.path.join(name, os.path.basename(patch)))
2585 name = normname(os.path.join(name, os.path.basename(patch)))
2586 absdest = q.join(name)
2586 absdest = q.join(name)
2587 q.checkpatchname(name)
2587 q.checkpatchname(name)
2588
2588
2589 ui.note(_('renaming %s to %s\n') % (patch, name))
2589 ui.note(_('renaming %s to %s\n') % (patch, name))
2590 i = q.findseries(patch)
2590 i = q.findseries(patch)
2591 guards = q.guard_re.findall(q.fullseries[i])
2591 guards = q.guard_re.findall(q.fullseries[i])
2592 q.fullseries[i] = name + ''.join([' #' + g for g in guards])
2592 q.fullseries[i] = name + ''.join([' #' + g for g in guards])
2593 q.parseseries()
2593 q.parseseries()
2594 q.seriesdirty = 1
2594 q.seriesdirty = 1
2595
2595
2596 info = q.isapplied(patch)
2596 info = q.isapplied(patch)
2597 if info:
2597 if info:
2598 q.applied[info[0]] = statusentry(info[1], name)
2598 q.applied[info[0]] = statusentry(info[1], name)
2599 q.applieddirty = 1
2599 q.applieddirty = 1
2600
2600
2601 destdir = os.path.dirname(absdest)
2601 destdir = os.path.dirname(absdest)
2602 if not os.path.isdir(destdir):
2602 if not os.path.isdir(destdir):
2603 os.makedirs(destdir)
2603 os.makedirs(destdir)
2604 util.rename(q.join(patch), absdest)
2604 util.rename(q.join(patch), absdest)
2605 r = q.qrepo()
2605 r = q.qrepo()
2606 if r and patch in r.dirstate:
2606 if r and patch in r.dirstate:
2607 wctx = r[None]
2607 wctx = r[None]
2608 wlock = r.wlock()
2608 wlock = r.wlock()
2609 try:
2609 try:
2610 if r.dirstate[patch] == 'a':
2610 if r.dirstate[patch] == 'a':
2611 r.dirstate.drop(patch)
2611 r.dirstate.drop(patch)
2612 r.dirstate.add(name)
2612 r.dirstate.add(name)
2613 else:
2613 else:
2614 if r.dirstate[name] == 'r':
2614 if r.dirstate[name] == 'r':
2615 wctx.undelete([name])
2615 wctx.undelete([name])
2616 wctx.copy(patch, name)
2616 wctx.copy(patch, name)
2617 wctx.forget([patch])
2617 wctx.forget([patch])
2618 finally:
2618 finally:
2619 wlock.release()
2619 wlock.release()
2620
2620
2621 q.savedirty()
2621 q.savedirty()
2622
2622
2623 @command("qrestore",
2623 @command("qrestore",
2624 [('d', 'delete', None, _('delete save entry')),
2624 [('d', 'delete', None, _('delete save entry')),
2625 ('u', 'update', None, _('update queue working directory'))],
2625 ('u', 'update', None, _('update queue working directory'))],
2626 _('hg qrestore [-d] [-u] REV'))
2626 _('hg qrestore [-d] [-u] REV'))
2627 def restore(ui, repo, rev, **opts):
2627 def restore(ui, repo, rev, **opts):
2628 """restore the queue state saved by a revision (DEPRECATED)
2628 """restore the queue state saved by a revision (DEPRECATED)
2629
2629
2630 This command is deprecated, use :hg:`rebase` instead."""
2630 This command is deprecated, use :hg:`rebase` instead."""
2631 rev = repo.lookup(rev)
2631 rev = repo.lookup(rev)
2632 q = repo.mq
2632 q = repo.mq
2633 q.restore(repo, rev, delete=opts.get('delete'),
2633 q.restore(repo, rev, delete=opts.get('delete'),
2634 qupdate=opts.get('update'))
2634 qupdate=opts.get('update'))
2635 q.savedirty()
2635 q.savedirty()
2636 return 0
2636 return 0
2637
2637
2638 @command("qsave",
2638 @command("qsave",
2639 [('c', 'copy', None, _('copy patch directory')),
2639 [('c', 'copy', None, _('copy patch directory')),
2640 ('n', 'name', '',
2640 ('n', 'name', '',
2641 _('copy directory name'), _('NAME')),
2641 _('copy directory name'), _('NAME')),
2642 ('e', 'empty', None, _('clear queue status file')),
2642 ('e', 'empty', None, _('clear queue status file')),
2643 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2643 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2644 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'))
2644 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'))
2645 def save(ui, repo, **opts):
2645 def save(ui, repo, **opts):
2646 """save current queue state (DEPRECATED)
2646 """save current queue state (DEPRECATED)
2647
2647
2648 This command is deprecated, use :hg:`rebase` instead."""
2648 This command is deprecated, use :hg:`rebase` instead."""
2649 q = repo.mq
2649 q = repo.mq
2650 message = cmdutil.logmessage(ui, opts)
2650 message = cmdutil.logmessage(ui, opts)
2651 ret = q.save(repo, msg=message)
2651 ret = q.save(repo, msg=message)
2652 if ret:
2652 if ret:
2653 return ret
2653 return ret
2654 q.savedirty()
2654 q.savedirty()
2655 if opts.get('copy'):
2655 if opts.get('copy'):
2656 path = q.path
2656 path = q.path
2657 if opts.get('name'):
2657 if opts.get('name'):
2658 newpath = os.path.join(q.basepath, opts.get('name'))
2658 newpath = os.path.join(q.basepath, opts.get('name'))
2659 if os.path.exists(newpath):
2659 if os.path.exists(newpath):
2660 if not os.path.isdir(newpath):
2660 if not os.path.isdir(newpath):
2661 raise util.Abort(_('destination %s exists and is not '
2661 raise util.Abort(_('destination %s exists and is not '
2662 'a directory') % newpath)
2662 'a directory') % newpath)
2663 if not opts.get('force'):
2663 if not opts.get('force'):
2664 raise util.Abort(_('destination %s exists, '
2664 raise util.Abort(_('destination %s exists, '
2665 'use -f to force') % newpath)
2665 'use -f to force') % newpath)
2666 else:
2666 else:
2667 newpath = savename(path)
2667 newpath = savename(path)
2668 ui.warn(_("copy %s to %s\n") % (path, newpath))
2668 ui.warn(_("copy %s to %s\n") % (path, newpath))
2669 util.copyfiles(path, newpath)
2669 util.copyfiles(path, newpath)
2670 if opts.get('empty'):
2670 if opts.get('empty'):
2671 try:
2671 try:
2672 os.unlink(q.join(q.statuspath))
2672 os.unlink(q.join(q.statuspath))
2673 except:
2673 except:
2674 pass
2674 pass
2675 return 0
2675 return 0
2676
2676
2677 @command("strip",
2677 @command("strip",
2678 [('f', 'force', None, _('force removal of changesets, discard '
2678 [('f', 'force', None, _('force removal of changesets, discard '
2679 'uncommitted changes (no backup)')),
2679 'uncommitted changes (no backup)')),
2680 ('b', 'backup', None, _('bundle only changesets with local revision'
2680 ('b', 'backup', None, _('bundle only changesets with local revision'
2681 ' number greater than REV which are not'
2681 ' number greater than REV which are not'
2682 ' descendants of REV (DEPRECATED)')),
2682 ' descendants of REV (DEPRECATED)')),
2683 ('n', 'no-backup', None, _('no backups')),
2683 ('n', 'no-backup', None, _('no backups')),
2684 ('', 'nobackup', None, _('no backups (DEPRECATED)')),
2684 ('', 'nobackup', None, _('no backups (DEPRECATED)')),
2685 ('k', 'keep', None, _("do not modify working copy during strip"))],
2685 ('k', 'keep', None, _("do not modify working copy during strip"))],
2686 _('hg strip [-k] [-f] [-n] REV...'))
2686 _('hg strip [-k] [-f] [-n] REV...'))
2687 def strip(ui, repo, *revs, **opts):
2687 def strip(ui, repo, *revs, **opts):
2688 """strip changesets and all their descendants from the repository
2688 """strip changesets and all their descendants from the repository
2689
2689
2690 The strip command removes the specified changesets and all their
2690 The strip command removes the specified changesets and all their
2691 descendants. If the working directory has uncommitted changes, the
2691 descendants. If the working directory has uncommitted changes, the
2692 operation is aborted unless the --force flag is supplied, in which
2692 operation is aborted unless the --force flag is supplied, in which
2693 case changes will be discarded.
2693 case changes will be discarded.
2694
2694
2695 If a parent of the working directory is stripped, then the working
2695 If a parent of the working directory is stripped, then the working
2696 directory will automatically be updated to the most recent
2696 directory will automatically be updated to the most recent
2697 available ancestor of the stripped parent after the operation
2697 available ancestor of the stripped parent after the operation
2698 completes.
2698 completes.
2699
2699
2700 Any stripped changesets are stored in ``.hg/strip-backup`` as a
2700 Any stripped changesets are stored in ``.hg/strip-backup`` as a
2701 bundle (see :hg:`help bundle` and :hg:`help unbundle`). They can
2701 bundle (see :hg:`help bundle` and :hg:`help unbundle`). They can
2702 be restored by running :hg:`unbundle .hg/strip-backup/BUNDLE`,
2702 be restored by running :hg:`unbundle .hg/strip-backup/BUNDLE`,
2703 where BUNDLE is the bundle file created by the strip. Note that
2703 where BUNDLE is the bundle file created by the strip. Note that
2704 the local revision numbers will in general be different after the
2704 the local revision numbers will in general be different after the
2705 restore.
2705 restore.
2706
2706
2707 Use the --no-backup option to discard the backup bundle once the
2707 Use the --no-backup option to discard the backup bundle once the
2708 operation completes.
2708 operation completes.
2709
2709
2710 Return 0 on success.
2710 Return 0 on success.
2711 """
2711 """
2712 backup = 'all'
2712 backup = 'all'
2713 if opts.get('backup'):
2713 if opts.get('backup'):
2714 backup = 'strip'
2714 backup = 'strip'
2715 elif opts.get('no_backup') or opts.get('nobackup'):
2715 elif opts.get('no_backup') or opts.get('nobackup'):
2716 backup = 'none'
2716 backup = 'none'
2717
2717
2718 cl = repo.changelog
2718 cl = repo.changelog
2719 revs = set(scmutil.revrange(repo, revs))
2719 revs = set(scmutil.revrange(repo, revs))
2720 if not revs:
2720 if not revs:
2721 raise util.Abort(_('empty revision set'))
2721 raise util.Abort(_('empty revision set'))
2722
2722
2723 descendants = set(cl.descendants(*revs))
2723 descendants = set(cl.descendants(*revs))
2724 strippedrevs = revs.union(descendants)
2724 strippedrevs = revs.union(descendants)
2725 roots = revs.difference(descendants)
2725 roots = revs.difference(descendants)
2726
2726
2727 update = False
2727 update = False
2728 # if one of the wdir parent is stripped we'll need
2728 # if one of the wdir parent is stripped we'll need
2729 # to update away to an earlier revision
2729 # to update away to an earlier revision
2730 for p in repo.dirstate.parents():
2730 for p in repo.dirstate.parents():
2731 if p != nullid and cl.rev(p) in strippedrevs:
2731 if p != nullid and cl.rev(p) in strippedrevs:
2732 update = True
2732 update = True
2733 break
2733 break
2734
2734
2735 rootnodes = set(cl.node(r) for r in roots)
2735 rootnodes = set(cl.node(r) for r in roots)
2736
2736
2737 q = repo.mq
2737 q = repo.mq
2738 if q.applied:
2738 if q.applied:
2739 # refresh queue state if we're about to strip
2739 # refresh queue state if we're about to strip
2740 # applied patches
2740 # applied patches
2741 if cl.rev(repo.lookup('qtip')) in strippedrevs:
2741 if cl.rev(repo.lookup('qtip')) in strippedrevs:
2742 q.applieddirty = True
2742 q.applieddirty = True
2743 start = 0
2743 start = 0
2744 end = len(q.applied)
2744 end = len(q.applied)
2745 for i, statusentry in enumerate(q.applied):
2745 for i, statusentry in enumerate(q.applied):
2746 if statusentry.node in rootnodes:
2746 if statusentry.node in rootnodes:
2747 # if one of the stripped roots is an applied
2747 # if one of the stripped roots is an applied
2748 # patch, only part of the queue is stripped
2748 # patch, only part of the queue is stripped
2749 start = i
2749 start = i
2750 break
2750 break
2751 del q.applied[start:end]
2751 del q.applied[start:end]
2752 q.savedirty()
2752 q.savedirty()
2753
2753
2754 revs = list(rootnodes)
2754 revs = list(rootnodes)
2755 if update and opts.get('keep'):
2755 if update and opts.get('keep'):
2756 wlock = repo.wlock()
2756 wlock = repo.wlock()
2757 try:
2757 try:
2758 urev = repo.mq.qparents(repo, revs[0])
2758 urev = repo.mq.qparents(repo, revs[0])
2759 repo.dirstate.rebuild(urev, repo[urev].manifest())
2759 repo.dirstate.rebuild(urev, repo[urev].manifest())
2760 repo.dirstate.write()
2760 repo.dirstate.write()
2761 update = False
2761 update = False
2762 finally:
2762 finally:
2763 wlock.release()
2763 wlock.release()
2764
2764
2765 repo.mq.strip(repo, revs, backup=backup, update=update,
2765 repo.mq.strip(repo, revs, backup=backup, update=update,
2766 force=opts.get('force'))
2766 force=opts.get('force'))
2767 return 0
2767 return 0
2768
2768
2769 @command("qselect",
2769 @command("qselect",
2770 [('n', 'none', None, _('disable all guards')),
2770 [('n', 'none', None, _('disable all guards')),
2771 ('s', 'series', None, _('list all guards in series file')),
2771 ('s', 'series', None, _('list all guards in series file')),
2772 ('', 'pop', None, _('pop to before first guarded applied patch')),
2772 ('', 'pop', None, _('pop to before first guarded applied patch')),
2773 ('', 'reapply', None, _('pop, then reapply patches'))],
2773 ('', 'reapply', None, _('pop, then reapply patches'))],
2774 _('hg qselect [OPTION]... [GUARD]...'))
2774 _('hg qselect [OPTION]... [GUARD]...'))
2775 def select(ui, repo, *args, **opts):
2775 def select(ui, repo, *args, **opts):
2776 '''set or print guarded patches to push
2776 '''set or print guarded patches to push
2777
2777
2778 Use the :hg:`qguard` command to set or print guards on patch, then use
2778 Use the :hg:`qguard` command to set or print guards on patch, then use
2779 qselect to tell mq which guards to use. A patch will be pushed if
2779 qselect to tell mq which guards to use. A patch will be pushed if
2780 it has no guards or any positive guards match the currently
2780 it has no guards or any positive guards match the currently
2781 selected guard, but will not be pushed if any negative guards
2781 selected guard, but will not be pushed if any negative guards
2782 match the current guard. For example::
2782 match the current guard. For example::
2783
2783
2784 qguard foo.patch -- -stable (negative guard)
2784 qguard foo.patch -- -stable (negative guard)
2785 qguard bar.patch +stable (positive guard)
2785 qguard bar.patch +stable (positive guard)
2786 qselect stable
2786 qselect stable
2787
2787
2788 This activates the "stable" guard. mq will skip foo.patch (because
2788 This activates the "stable" guard. mq will skip foo.patch (because
2789 it has a negative match) but push bar.patch (because it has a
2789 it has a negative match) but push bar.patch (because it has a
2790 positive match).
2790 positive match).
2791
2791
2792 With no arguments, prints the currently active guards.
2792 With no arguments, prints the currently active guards.
2793 With one argument, sets the active guard.
2793 With one argument, sets the active guard.
2794
2794
2795 Use -n/--none to deactivate guards (no other arguments needed).
2795 Use -n/--none to deactivate guards (no other arguments needed).
2796 When no guards are active, patches with positive guards are
2796 When no guards are active, patches with positive guards are
2797 skipped and patches with negative guards are pushed.
2797 skipped and patches with negative guards are pushed.
2798
2798
2799 qselect can change the guards on applied patches. It does not pop
2799 qselect can change the guards on applied patches. It does not pop
2800 guarded patches by default. Use --pop to pop back to the last
2800 guarded patches by default. Use --pop to pop back to the last
2801 applied patch that is not guarded. Use --reapply (which implies
2801 applied patch that is not guarded. Use --reapply (which implies
2802 --pop) to push back to the current patch afterwards, but skip
2802 --pop) to push back to the current patch afterwards, but skip
2803 guarded patches.
2803 guarded patches.
2804
2804
2805 Use -s/--series to print a list of all guards in the series file
2805 Use -s/--series to print a list of all guards in the series file
2806 (no other arguments needed). Use -v for more information.
2806 (no other arguments needed). Use -v for more information.
2807
2807
2808 Returns 0 on success.'''
2808 Returns 0 on success.'''
2809
2809
2810 q = repo.mq
2810 q = repo.mq
2811 guards = q.active()
2811 guards = q.active()
2812 if args or opts.get('none'):
2812 if args or opts.get('none'):
2813 old_unapplied = q.unapplied(repo)
2813 old_unapplied = q.unapplied(repo)
2814 old_guarded = [i for i in xrange(len(q.applied)) if
2814 old_guarded = [i for i in xrange(len(q.applied)) if
2815 not q.pushable(i)[0]]
2815 not q.pushable(i)[0]]
2816 q.setactive(args)
2816 q.setactive(args)
2817 q.savedirty()
2817 q.savedirty()
2818 if not args:
2818 if not args:
2819 ui.status(_('guards deactivated\n'))
2819 ui.status(_('guards deactivated\n'))
2820 if not opts.get('pop') and not opts.get('reapply'):
2820 if not opts.get('pop') and not opts.get('reapply'):
2821 unapplied = q.unapplied(repo)
2821 unapplied = q.unapplied(repo)
2822 guarded = [i for i in xrange(len(q.applied))
2822 guarded = [i for i in xrange(len(q.applied))
2823 if not q.pushable(i)[0]]
2823 if not q.pushable(i)[0]]
2824 if len(unapplied) != len(old_unapplied):
2824 if len(unapplied) != len(old_unapplied):
2825 ui.status(_('number of unguarded, unapplied patches has '
2825 ui.status(_('number of unguarded, unapplied patches has '
2826 'changed from %d to %d\n') %
2826 'changed from %d to %d\n') %
2827 (len(old_unapplied), len(unapplied)))
2827 (len(old_unapplied), len(unapplied)))
2828 if len(guarded) != len(old_guarded):
2828 if len(guarded) != len(old_guarded):
2829 ui.status(_('number of guarded, applied patches has changed '
2829 ui.status(_('number of guarded, applied patches has changed '
2830 'from %d to %d\n') %
2830 'from %d to %d\n') %
2831 (len(old_guarded), len(guarded)))
2831 (len(old_guarded), len(guarded)))
2832 elif opts.get('series'):
2832 elif opts.get('series'):
2833 guards = {}
2833 guards = {}
2834 noguards = 0
2834 noguards = 0
2835 for gs in q.seriesguards:
2835 for gs in q.seriesguards:
2836 if not gs:
2836 if not gs:
2837 noguards += 1
2837 noguards += 1
2838 for g in gs:
2838 for g in gs:
2839 guards.setdefault(g, 0)
2839 guards.setdefault(g, 0)
2840 guards[g] += 1
2840 guards[g] += 1
2841 if ui.verbose:
2841 if ui.verbose:
2842 guards['NONE'] = noguards
2842 guards['NONE'] = noguards
2843 guards = guards.items()
2843 guards = guards.items()
2844 guards.sort(key=lambda x: x[0][1:])
2844 guards.sort(key=lambda x: x[0][1:])
2845 if guards:
2845 if guards:
2846 ui.note(_('guards in series file:\n'))
2846 ui.note(_('guards in series file:\n'))
2847 for guard, count in guards:
2847 for guard, count in guards:
2848 ui.note('%2d ' % count)
2848 ui.note('%2d ' % count)
2849 ui.write(guard, '\n')
2849 ui.write(guard, '\n')
2850 else:
2850 else:
2851 ui.note(_('no guards in series file\n'))
2851 ui.note(_('no guards in series file\n'))
2852 else:
2852 else:
2853 if guards:
2853 if guards:
2854 ui.note(_('active guards:\n'))
2854 ui.note(_('active guards:\n'))
2855 for g in guards:
2855 for g in guards:
2856 ui.write(g, '\n')
2856 ui.write(g, '\n')
2857 else:
2857 else:
2858 ui.write(_('no active guards\n'))
2858 ui.write(_('no active guards\n'))
2859 reapply = opts.get('reapply') and q.applied and q.appliedname(-1)
2859 reapply = opts.get('reapply') and q.applied and q.appliedname(-1)
2860 popped = False
2860 popped = False
2861 if opts.get('pop') or opts.get('reapply'):
2861 if opts.get('pop') or opts.get('reapply'):
2862 for i in xrange(len(q.applied)):
2862 for i in xrange(len(q.applied)):
2863 pushable, reason = q.pushable(i)
2863 pushable, reason = q.pushable(i)
2864 if not pushable:
2864 if not pushable:
2865 ui.status(_('popping guarded patches\n'))
2865 ui.status(_('popping guarded patches\n'))
2866 popped = True
2866 popped = True
2867 if i == 0:
2867 if i == 0:
2868 q.pop(repo, all=True)
2868 q.pop(repo, all=True)
2869 else:
2869 else:
2870 q.pop(repo, i - 1)
2870 q.pop(repo, i - 1)
2871 break
2871 break
2872 if popped:
2872 if popped:
2873 try:
2873 try:
2874 if reapply:
2874 if reapply:
2875 ui.status(_('reapplying unguarded patches\n'))
2875 ui.status(_('reapplying unguarded patches\n'))
2876 q.push(repo, reapply)
2876 q.push(repo, reapply)
2877 finally:
2877 finally:
2878 q.savedirty()
2878 q.savedirty()
2879
2879
2880 @command("qfinish",
2880 @command("qfinish",
2881 [('a', 'applied', None, _('finish all applied changesets'))],
2881 [('a', 'applied', None, _('finish all applied changesets'))],
2882 _('hg qfinish [-a] [REV]...'))
2882 _('hg qfinish [-a] [REV]...'))
2883 def finish(ui, repo, *revrange, **opts):
2883 def finish(ui, repo, *revrange, **opts):
2884 """move applied patches into repository history
2884 """move applied patches into repository history
2885
2885
2886 Finishes the specified revisions (corresponding to applied
2886 Finishes the specified revisions (corresponding to applied
2887 patches) by moving them out of mq control into regular repository
2887 patches) by moving them out of mq control into regular repository
2888 history.
2888 history.
2889
2889
2890 Accepts a revision range or the -a/--applied option. If --applied
2890 Accepts a revision range or the -a/--applied option. If --applied
2891 is specified, all applied mq revisions are removed from mq
2891 is specified, all applied mq revisions are removed from mq
2892 control. Otherwise, the given revisions must be at the base of the
2892 control. Otherwise, the given revisions must be at the base of the
2893 stack of applied patches.
2893 stack of applied patches.
2894
2894
2895 This can be especially useful if your changes have been applied to
2895 This can be especially useful if your changes have been applied to
2896 an upstream repository, or if you are about to push your changes
2896 an upstream repository, or if you are about to push your changes
2897 to upstream.
2897 to upstream.
2898
2898
2899 Returns 0 on success.
2899 Returns 0 on success.
2900 """
2900 """
2901 if not opts.get('applied') and not revrange:
2901 if not opts.get('applied') and not revrange:
2902 raise util.Abort(_('no revisions specified'))
2902 raise util.Abort(_('no revisions specified'))
2903 elif opts.get('applied'):
2903 elif opts.get('applied'):
2904 revrange = ('qbase::qtip',) + revrange
2904 revrange = ('qbase::qtip',) + revrange
2905
2905
2906 q = repo.mq
2906 q = repo.mq
2907 if not q.applied:
2907 if not q.applied:
2908 ui.status(_('no patches applied\n'))
2908 ui.status(_('no patches applied\n'))
2909 return 0
2909 return 0
2910
2910
2911 revs = scmutil.revrange(repo, revrange)
2911 revs = scmutil.revrange(repo, revrange)
2912 q.finish(repo, revs)
2912 q.finish(repo, revs)
2913 q.savedirty()
2913 q.savedirty()
2914 return 0
2914 return 0
2915
2915
2916 @command("qqueue",
2916 @command("qqueue",
2917 [('l', 'list', False, _('list all available queues')),
2917 [('l', 'list', False, _('list all available queues')),
2918 ('', 'active', False, _('print name of active queue')),
2918 ('c', 'create', False, _('create new queue')),
2919 ('c', 'create', False, _('create new queue')),
2919 ('', 'rename', False, _('rename active queue')),
2920 ('', 'rename', False, _('rename active queue')),
2920 ('', 'delete', False, _('delete reference to queue')),
2921 ('', 'delete', False, _('delete reference to queue')),
2921 ('', 'purge', False, _('delete queue, and remove patch dir')),
2922 ('', 'purge', False, _('delete queue, and remove patch dir')),
2922 ],
2923 ],
2923 _('[OPTION] [QUEUE]'))
2924 _('[OPTION] [QUEUE]'))
2924 def qqueue(ui, repo, name=None, **opts):
2925 def qqueue(ui, repo, name=None, **opts):
2925 '''manage multiple patch queues
2926 '''manage multiple patch queues
2926
2927
2927 Supports switching between different patch queues, as well as creating
2928 Supports switching between different patch queues, as well as creating
2928 new patch queues and deleting existing ones.
2929 new patch queues and deleting existing ones.
2929
2930
2930 Omitting a queue name or specifying -l/--list will show you the registered
2931 Omitting a queue name or specifying -l/--list will show you the registered
2931 queues - by default the "normal" patches queue is registered. The currently
2932 queues - by default the "normal" patches queue is registered. The currently
2932 active queue will be marked with "(active)".
2933 active queue will be marked with "(active)". Specifying --active will print
2934 only the name of the active queue.
2933
2935
2934 To create a new queue, use -c/--create. The queue is automatically made
2936 To create a new queue, use -c/--create. The queue is automatically made
2935 active, except in the case where there are applied patches from the
2937 active, except in the case where there are applied patches from the
2936 currently active queue in the repository. Then the queue will only be
2938 currently active queue in the repository. Then the queue will only be
2937 created and switching will fail.
2939 created and switching will fail.
2938
2940
2939 To delete an existing queue, use --delete. You cannot delete the currently
2941 To delete an existing queue, use --delete. You cannot delete the currently
2940 active queue.
2942 active queue.
2941
2943
2942 Returns 0 on success.
2944 Returns 0 on success.
2943 '''
2945 '''
2944
2946
2945 q = repo.mq
2947 q = repo.mq
2946
2948
2947 _defaultqueue = 'patches'
2949 _defaultqueue = 'patches'
2948 _allqueues = 'patches.queues'
2950 _allqueues = 'patches.queues'
2949 _activequeue = 'patches.queue'
2951 _activequeue = 'patches.queue'
2950
2952
2951 def _getcurrent():
2953 def _getcurrent():
2952 cur = os.path.basename(q.path)
2954 cur = os.path.basename(q.path)
2953 if cur.startswith('patches-'):
2955 if cur.startswith('patches-'):
2954 cur = cur[8:]
2956 cur = cur[8:]
2955 return cur
2957 return cur
2956
2958
2957 def _noqueues():
2959 def _noqueues():
2958 try:
2960 try:
2959 fh = repo.opener(_allqueues, 'r')
2961 fh = repo.opener(_allqueues, 'r')
2960 fh.close()
2962 fh.close()
2961 except IOError:
2963 except IOError:
2962 return True
2964 return True
2963
2965
2964 return False
2966 return False
2965
2967
2966 def _getqueues():
2968 def _getqueues():
2967 current = _getcurrent()
2969 current = _getcurrent()
2968
2970
2969 try:
2971 try:
2970 fh = repo.opener(_allqueues, 'r')
2972 fh = repo.opener(_allqueues, 'r')
2971 queues = [queue.strip() for queue in fh if queue.strip()]
2973 queues = [queue.strip() for queue in fh if queue.strip()]
2972 fh.close()
2974 fh.close()
2973 if current not in queues:
2975 if current not in queues:
2974 queues.append(current)
2976 queues.append(current)
2975 except IOError:
2977 except IOError:
2976 queues = [_defaultqueue]
2978 queues = [_defaultqueue]
2977
2979
2978 return sorted(queues)
2980 return sorted(queues)
2979
2981
2980 def _setactive(name):
2982 def _setactive(name):
2981 if q.applied:
2983 if q.applied:
2982 raise util.Abort(_('patches applied - cannot set new queue active'))
2984 raise util.Abort(_('patches applied - cannot set new queue active'))
2983 _setactivenocheck(name)
2985 _setactivenocheck(name)
2984
2986
2985 def _setactivenocheck(name):
2987 def _setactivenocheck(name):
2986 fh = repo.opener(_activequeue, 'w')
2988 fh = repo.opener(_activequeue, 'w')
2987 if name != 'patches':
2989 if name != 'patches':
2988 fh.write(name)
2990 fh.write(name)
2989 fh.close()
2991 fh.close()
2990
2992
2991 def _addqueue(name):
2993 def _addqueue(name):
2992 fh = repo.opener(_allqueues, 'a')
2994 fh = repo.opener(_allqueues, 'a')
2993 fh.write('%s\n' % (name,))
2995 fh.write('%s\n' % (name,))
2994 fh.close()
2996 fh.close()
2995
2997
2996 def _queuedir(name):
2998 def _queuedir(name):
2997 if name == 'patches':
2999 if name == 'patches':
2998 return repo.join('patches')
3000 return repo.join('patches')
2999 else:
3001 else:
3000 return repo.join('patches-' + name)
3002 return repo.join('patches-' + name)
3001
3003
3002 def _validname(name):
3004 def _validname(name):
3003 for n in name:
3005 for n in name:
3004 if n in ':\\/.':
3006 if n in ':\\/.':
3005 return False
3007 return False
3006 return True
3008 return True
3007
3009
3008 def _delete(name):
3010 def _delete(name):
3009 if name not in existing:
3011 if name not in existing:
3010 raise util.Abort(_('cannot delete queue that does not exist'))
3012 raise util.Abort(_('cannot delete queue that does not exist'))
3011
3013
3012 current = _getcurrent()
3014 current = _getcurrent()
3013
3015
3014 if name == current:
3016 if name == current:
3015 raise util.Abort(_('cannot delete currently active queue'))
3017 raise util.Abort(_('cannot delete currently active queue'))
3016
3018
3017 fh = repo.opener('patches.queues.new', 'w')
3019 fh = repo.opener('patches.queues.new', 'w')
3018 for queue in existing:
3020 for queue in existing:
3019 if queue == name:
3021 if queue == name:
3020 continue
3022 continue
3021 fh.write('%s\n' % (queue,))
3023 fh.write('%s\n' % (queue,))
3022 fh.close()
3024 fh.close()
3023 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3025 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3024
3026
3025 if not name or opts.get('list'):
3027 if not name or opts.get('list') or opts.get('active'):
3026 current = _getcurrent()
3028 current = _getcurrent()
3029 if opts.get('active'):
3030 ui.write('%s\n' % (current,))
3031 return
3027 for queue in _getqueues():
3032 for queue in _getqueues():
3028 ui.write('%s' % (queue,))
3033 ui.write('%s' % (queue,))
3029 if queue == current and not ui.quiet:
3034 if queue == current and not ui.quiet:
3030 ui.write(_(' (active)\n'))
3035 ui.write(_(' (active)\n'))
3031 else:
3036 else:
3032 ui.write('\n')
3037 ui.write('\n')
3033 return
3038 return
3034
3039
3035 if not _validname(name):
3040 if not _validname(name):
3036 raise util.Abort(
3041 raise util.Abort(
3037 _('invalid queue name, may not contain the characters ":\\/."'))
3042 _('invalid queue name, may not contain the characters ":\\/."'))
3038
3043
3039 existing = _getqueues()
3044 existing = _getqueues()
3040
3045
3041 if opts.get('create'):
3046 if opts.get('create'):
3042 if name in existing:
3047 if name in existing:
3043 raise util.Abort(_('queue "%s" already exists') % name)
3048 raise util.Abort(_('queue "%s" already exists') % name)
3044 if _noqueues():
3049 if _noqueues():
3045 _addqueue(_defaultqueue)
3050 _addqueue(_defaultqueue)
3046 _addqueue(name)
3051 _addqueue(name)
3047 _setactive(name)
3052 _setactive(name)
3048 elif opts.get('rename'):
3053 elif opts.get('rename'):
3049 current = _getcurrent()
3054 current = _getcurrent()
3050 if name == current:
3055 if name == current:
3051 raise util.Abort(_('can\'t rename "%s" to its current name') % name)
3056 raise util.Abort(_('can\'t rename "%s" to its current name') % name)
3052 if name in existing:
3057 if name in existing:
3053 raise util.Abort(_('queue "%s" already exists') % name)
3058 raise util.Abort(_('queue "%s" already exists') % name)
3054
3059
3055 olddir = _queuedir(current)
3060 olddir = _queuedir(current)
3056 newdir = _queuedir(name)
3061 newdir = _queuedir(name)
3057
3062
3058 if os.path.exists(newdir):
3063 if os.path.exists(newdir):
3059 raise util.Abort(_('non-queue directory "%s" already exists') %
3064 raise util.Abort(_('non-queue directory "%s" already exists') %
3060 newdir)
3065 newdir)
3061
3066
3062 fh = repo.opener('patches.queues.new', 'w')
3067 fh = repo.opener('patches.queues.new', 'w')
3063 for queue in existing:
3068 for queue in existing:
3064 if queue == current:
3069 if queue == current:
3065 fh.write('%s\n' % (name,))
3070 fh.write('%s\n' % (name,))
3066 if os.path.exists(olddir):
3071 if os.path.exists(olddir):
3067 util.rename(olddir, newdir)
3072 util.rename(olddir, newdir)
3068 else:
3073 else:
3069 fh.write('%s\n' % (queue,))
3074 fh.write('%s\n' % (queue,))
3070 fh.close()
3075 fh.close()
3071 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3076 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3072 _setactivenocheck(name)
3077 _setactivenocheck(name)
3073 elif opts.get('delete'):
3078 elif opts.get('delete'):
3074 _delete(name)
3079 _delete(name)
3075 elif opts.get('purge'):
3080 elif opts.get('purge'):
3076 if name in existing:
3081 if name in existing:
3077 _delete(name)
3082 _delete(name)
3078 qdir = _queuedir(name)
3083 qdir = _queuedir(name)
3079 if os.path.exists(qdir):
3084 if os.path.exists(qdir):
3080 shutil.rmtree(qdir)
3085 shutil.rmtree(qdir)
3081 else:
3086 else:
3082 if name not in existing:
3087 if name not in existing:
3083 raise util.Abort(_('use --create to create a new queue'))
3088 raise util.Abort(_('use --create to create a new queue'))
3084 _setactive(name)
3089 _setactive(name)
3085
3090
3086 def reposetup(ui, repo):
3091 def reposetup(ui, repo):
3087 class mqrepo(repo.__class__):
3092 class mqrepo(repo.__class__):
3088 @util.propertycache
3093 @util.propertycache
3089 def mq(self):
3094 def mq(self):
3090 return queue(self.ui, self.join(""))
3095 return queue(self.ui, self.join(""))
3091
3096
3092 def abortifwdirpatched(self, errmsg, force=False):
3097 def abortifwdirpatched(self, errmsg, force=False):
3093 if self.mq.applied and not force:
3098 if self.mq.applied and not force:
3094 parents = self.dirstate.parents()
3099 parents = self.dirstate.parents()
3095 patches = [s.node for s in self.mq.applied]
3100 patches = [s.node for s in self.mq.applied]
3096 if parents[0] in patches or parents[1] in patches:
3101 if parents[0] in patches or parents[1] in patches:
3097 raise util.Abort(errmsg)
3102 raise util.Abort(errmsg)
3098
3103
3099 def commit(self, text="", user=None, date=None, match=None,
3104 def commit(self, text="", user=None, date=None, match=None,
3100 force=False, editor=False, extra={}):
3105 force=False, editor=False, extra={}):
3101 self.abortifwdirpatched(
3106 self.abortifwdirpatched(
3102 _('cannot commit over an applied mq patch'),
3107 _('cannot commit over an applied mq patch'),
3103 force)
3108 force)
3104
3109
3105 return super(mqrepo, self).commit(text, user, date, match, force,
3110 return super(mqrepo, self).commit(text, user, date, match, force,
3106 editor, extra)
3111 editor, extra)
3107
3112
3108 def checkpush(self, force, revs):
3113 def checkpush(self, force, revs):
3109 if self.mq.applied and not force:
3114 if self.mq.applied and not force:
3110 haspatches = True
3115 haspatches = True
3111 if revs:
3116 if revs:
3112 # Assume applied patches have no non-patch descendants
3117 # Assume applied patches have no non-patch descendants
3113 # and are not on remote already. If they appear in the
3118 # and are not on remote already. If they appear in the
3114 # set of resolved 'revs', bail out.
3119 # set of resolved 'revs', bail out.
3115 applied = set(e.node for e in self.mq.applied)
3120 applied = set(e.node for e in self.mq.applied)
3116 haspatches = bool([n for n in revs if n in applied])
3121 haspatches = bool([n for n in revs if n in applied])
3117 if haspatches:
3122 if haspatches:
3118 raise util.Abort(_('source has mq patches applied'))
3123 raise util.Abort(_('source has mq patches applied'))
3119 super(mqrepo, self).checkpush(force, revs)
3124 super(mqrepo, self).checkpush(force, revs)
3120
3125
3121 def _findtags(self):
3126 def _findtags(self):
3122 '''augment tags from base class with patch tags'''
3127 '''augment tags from base class with patch tags'''
3123 result = super(mqrepo, self)._findtags()
3128 result = super(mqrepo, self)._findtags()
3124
3129
3125 q = self.mq
3130 q = self.mq
3126 if not q.applied:
3131 if not q.applied:
3127 return result
3132 return result
3128
3133
3129 mqtags = [(patch.node, patch.name) for patch in q.applied]
3134 mqtags = [(patch.node, patch.name) for patch in q.applied]
3130
3135
3131 try:
3136 try:
3132 self.changelog.rev(mqtags[-1][0])
3137 self.changelog.rev(mqtags[-1][0])
3133 except error.LookupError:
3138 except error.LookupError:
3134 self.ui.warn(_('mq status file refers to unknown node %s\n')
3139 self.ui.warn(_('mq status file refers to unknown node %s\n')
3135 % short(mqtags[-1][0]))
3140 % short(mqtags[-1][0]))
3136 return result
3141 return result
3137
3142
3138 mqtags.append((mqtags[-1][0], 'qtip'))
3143 mqtags.append((mqtags[-1][0], 'qtip'))
3139 mqtags.append((mqtags[0][0], 'qbase'))
3144 mqtags.append((mqtags[0][0], 'qbase'))
3140 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
3145 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
3141 tags = result[0]
3146 tags = result[0]
3142 for patch in mqtags:
3147 for patch in mqtags:
3143 if patch[1] in tags:
3148 if patch[1] in tags:
3144 self.ui.warn(_('Tag %s overrides mq patch of the same name\n')
3149 self.ui.warn(_('Tag %s overrides mq patch of the same name\n')
3145 % patch[1])
3150 % patch[1])
3146 else:
3151 else:
3147 tags[patch[1]] = patch[0]
3152 tags[patch[1]] = patch[0]
3148
3153
3149 return result
3154 return result
3150
3155
3151 def _branchtags(self, partial, lrev):
3156 def _branchtags(self, partial, lrev):
3152 q = self.mq
3157 q = self.mq
3153 if not q.applied:
3158 if not q.applied:
3154 return super(mqrepo, self)._branchtags(partial, lrev)
3159 return super(mqrepo, self)._branchtags(partial, lrev)
3155
3160
3156 cl = self.changelog
3161 cl = self.changelog
3157 qbasenode = q.applied[0].node
3162 qbasenode = q.applied[0].node
3158 try:
3163 try:
3159 qbase = cl.rev(qbasenode)
3164 qbase = cl.rev(qbasenode)
3160 except error.LookupError:
3165 except error.LookupError:
3161 self.ui.warn(_('mq status file refers to unknown node %s\n')
3166 self.ui.warn(_('mq status file refers to unknown node %s\n')
3162 % short(qbasenode))
3167 % short(qbasenode))
3163 return super(mqrepo, self)._branchtags(partial, lrev)
3168 return super(mqrepo, self)._branchtags(partial, lrev)
3164
3169
3165 start = lrev + 1
3170 start = lrev + 1
3166 if start < qbase:
3171 if start < qbase:
3167 # update the cache (excluding the patches) and save it
3172 # update the cache (excluding the patches) and save it
3168 ctxgen = (self[r] for r in xrange(lrev + 1, qbase))
3173 ctxgen = (self[r] for r in xrange(lrev + 1, qbase))
3169 self._updatebranchcache(partial, ctxgen)
3174 self._updatebranchcache(partial, ctxgen)
3170 self._writebranchcache(partial, cl.node(qbase - 1), qbase - 1)
3175 self._writebranchcache(partial, cl.node(qbase - 1), qbase - 1)
3171 start = qbase
3176 start = qbase
3172 # if start = qbase, the cache is as updated as it should be.
3177 # if start = qbase, the cache is as updated as it should be.
3173 # if start > qbase, the cache includes (part of) the patches.
3178 # if start > qbase, the cache includes (part of) the patches.
3174 # we might as well use it, but we won't save it.
3179 # we might as well use it, but we won't save it.
3175
3180
3176 # update the cache up to the tip
3181 # update the cache up to the tip
3177 ctxgen = (self[r] for r in xrange(start, len(cl)))
3182 ctxgen = (self[r] for r in xrange(start, len(cl)))
3178 self._updatebranchcache(partial, ctxgen)
3183 self._updatebranchcache(partial, ctxgen)
3179
3184
3180 return partial
3185 return partial
3181
3186
3182 if repo.local():
3187 if repo.local():
3183 repo.__class__ = mqrepo
3188 repo.__class__ = mqrepo
3184
3189
3185 def mqimport(orig, ui, repo, *args, **kwargs):
3190 def mqimport(orig, ui, repo, *args, **kwargs):
3186 if (hasattr(repo, 'abortifwdirpatched')
3191 if (hasattr(repo, 'abortifwdirpatched')
3187 and not kwargs.get('no_commit', False)):
3192 and not kwargs.get('no_commit', False)):
3188 repo.abortifwdirpatched(_('cannot import over an applied patch'),
3193 repo.abortifwdirpatched(_('cannot import over an applied patch'),
3189 kwargs.get('force'))
3194 kwargs.get('force'))
3190 return orig(ui, repo, *args, **kwargs)
3195 return orig(ui, repo, *args, **kwargs)
3191
3196
3192 def mqinit(orig, ui, *args, **kwargs):
3197 def mqinit(orig, ui, *args, **kwargs):
3193 mq = kwargs.pop('mq', None)
3198 mq = kwargs.pop('mq', None)
3194
3199
3195 if not mq:
3200 if not mq:
3196 return orig(ui, *args, **kwargs)
3201 return orig(ui, *args, **kwargs)
3197
3202
3198 if args:
3203 if args:
3199 repopath = args[0]
3204 repopath = args[0]
3200 if not hg.islocal(repopath):
3205 if not hg.islocal(repopath):
3201 raise util.Abort(_('only a local queue repository '
3206 raise util.Abort(_('only a local queue repository '
3202 'may be initialized'))
3207 'may be initialized'))
3203 else:
3208 else:
3204 repopath = cmdutil.findrepo(os.getcwd())
3209 repopath = cmdutil.findrepo(os.getcwd())
3205 if not repopath:
3210 if not repopath:
3206 raise util.Abort(_('there is no Mercurial repository here '
3211 raise util.Abort(_('there is no Mercurial repository here '
3207 '(.hg not found)'))
3212 '(.hg not found)'))
3208 repo = hg.repository(ui, repopath)
3213 repo = hg.repository(ui, repopath)
3209 return qinit(ui, repo, True)
3214 return qinit(ui, repo, True)
3210
3215
3211 def mqcommand(orig, ui, repo, *args, **kwargs):
3216 def mqcommand(orig, ui, repo, *args, **kwargs):
3212 """Add --mq option to operate on patch repository instead of main"""
3217 """Add --mq option to operate on patch repository instead of main"""
3213
3218
3214 # some commands do not like getting unknown options
3219 # some commands do not like getting unknown options
3215 mq = kwargs.pop('mq', None)
3220 mq = kwargs.pop('mq', None)
3216
3221
3217 if not mq:
3222 if not mq:
3218 return orig(ui, repo, *args, **kwargs)
3223 return orig(ui, repo, *args, **kwargs)
3219
3224
3220 q = repo.mq
3225 q = repo.mq
3221 r = q.qrepo()
3226 r = q.qrepo()
3222 if not r:
3227 if not r:
3223 raise util.Abort(_('no queue repository'))
3228 raise util.Abort(_('no queue repository'))
3224 return orig(r.ui, r, *args, **kwargs)
3229 return orig(r.ui, r, *args, **kwargs)
3225
3230
3226 def summary(orig, ui, repo, *args, **kwargs):
3231 def summary(orig, ui, repo, *args, **kwargs):
3227 r = orig(ui, repo, *args, **kwargs)
3232 r = orig(ui, repo, *args, **kwargs)
3228 q = repo.mq
3233 q = repo.mq
3229 m = []
3234 m = []
3230 a, u = len(q.applied), len(q.unapplied(repo))
3235 a, u = len(q.applied), len(q.unapplied(repo))
3231 if a:
3236 if a:
3232 m.append(ui.label(_("%d applied"), 'qseries.applied') % a)
3237 m.append(ui.label(_("%d applied"), 'qseries.applied') % a)
3233 if u:
3238 if u:
3234 m.append(ui.label(_("%d unapplied"), 'qseries.unapplied') % u)
3239 m.append(ui.label(_("%d unapplied"), 'qseries.unapplied') % u)
3235 if m:
3240 if m:
3236 ui.write("mq: %s\n" % ', '.join(m))
3241 ui.write("mq: %s\n" % ', '.join(m))
3237 else:
3242 else:
3238 ui.note(_("mq: (empty queue)\n"))
3243 ui.note(_("mq: (empty queue)\n"))
3239 return r
3244 return r
3240
3245
3241 def revsetmq(repo, subset, x):
3246 def revsetmq(repo, subset, x):
3242 """``mq()``
3247 """``mq()``
3243 Changesets managed by MQ.
3248 Changesets managed by MQ.
3244 """
3249 """
3245 revset.getargs(x, 0, 0, _("mq takes no arguments"))
3250 revset.getargs(x, 0, 0, _("mq takes no arguments"))
3246 applied = set([repo[r.node].rev() for r in repo.mq.applied])
3251 applied = set([repo[r.node].rev() for r in repo.mq.applied])
3247 return [r for r in subset if r in applied]
3252 return [r for r in subset if r in applied]
3248
3253
3249 def extsetup(ui):
3254 def extsetup(ui):
3250 revset.symbols['mq'] = revsetmq
3255 revset.symbols['mq'] = revsetmq
3251
3256
3252 # tell hggettext to extract docstrings from these functions:
3257 # tell hggettext to extract docstrings from these functions:
3253 i18nfunctions = [revsetmq]
3258 i18nfunctions = [revsetmq]
3254
3259
3255 def uisetup(ui):
3260 def uisetup(ui):
3256 mqopt = [('', 'mq', None, _("operate on patch repository"))]
3261 mqopt = [('', 'mq', None, _("operate on patch repository"))]
3257
3262
3258 extensions.wrapcommand(commands.table, 'import', mqimport)
3263 extensions.wrapcommand(commands.table, 'import', mqimport)
3259 extensions.wrapcommand(commands.table, 'summary', summary)
3264 extensions.wrapcommand(commands.table, 'summary', summary)
3260
3265
3261 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
3266 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
3262 entry[1].extend(mqopt)
3267 entry[1].extend(mqopt)
3263
3268
3264 nowrap = set(commands.norepo.split(" "))
3269 nowrap = set(commands.norepo.split(" "))
3265
3270
3266 def dotable(cmdtable):
3271 def dotable(cmdtable):
3267 for cmd in cmdtable.keys():
3272 for cmd in cmdtable.keys():
3268 cmd = cmdutil.parsealiases(cmd)[0]
3273 cmd = cmdutil.parsealiases(cmd)[0]
3269 if cmd in nowrap:
3274 if cmd in nowrap:
3270 continue
3275 continue
3271 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
3276 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
3272 entry[1].extend(mqopt)
3277 entry[1].extend(mqopt)
3273
3278
3274 dotable(commands.table)
3279 dotable(commands.table)
3275
3280
3276 for extname, extmodule in extensions.extensions():
3281 for extname, extmodule in extensions.extensions():
3277 if extmodule.__file__ != __file__:
3282 if extmodule.__file__ != __file__:
3278 dotable(getattr(extmodule, 'cmdtable', {}))
3283 dotable(getattr(extmodule, 'cmdtable', {}))
3279
3284
3280
3285
3281 colortable = {'qguard.negative': 'red',
3286 colortable = {'qguard.negative': 'red',
3282 'qguard.positive': 'yellow',
3287 'qguard.positive': 'yellow',
3283 'qguard.unguarded': 'green',
3288 'qguard.unguarded': 'green',
3284 'qseries.applied': 'blue bold underline',
3289 'qseries.applied': 'blue bold underline',
3285 'qseries.guarded': 'black bold',
3290 'qseries.guarded': 'black bold',
3286 'qseries.missing': 'red bold',
3291 'qseries.missing': 'red bold',
3287 'qseries.unapplied': 'black bold'}
3292 'qseries.unapplied': 'black bold'}
General Comments 0
You need to be logged in to leave comments. Login now