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