##// END OF EJS Templates
merge with stable
Matt Mackall -
r16699:d947e1da merge default
parent child Browse files
Show More

The requested changes are too big and content was truncated. Show full diff

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