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