##// END OF EJS Templates
match: use match.files() for patch.diff
Matt Mackall -
r6601:cab3ad86 default
parent child Browse files
Show More
@@ -1,358 +1,358 b''
1 # Minimal support for git commands on an hg repository
1 # Minimal support for git commands on an hg repository
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
5 # This software may be used and distributed according to the terms
6 # of the GNU General Public License, incorporated herein by reference.
6 # of the GNU General Public License, incorporated herein by reference.
7 #
7 #
8 # The hgk extension allows browsing the history of a repository in a
8 # The hgk extension allows browsing the history of a repository in a
9 # graphical way. It requires Tcl/Tk version 8.4 or later. (Tcl/Tk is
9 # graphical way. It requires Tcl/Tk version 8.4 or later. (Tcl/Tk is
10 # not distributed with Mercurial.)
10 # not distributed with Mercurial.)
11 #
11 #
12 # hgk consists of two parts: a Tcl script that does the displaying and
12 # hgk consists of two parts: a Tcl script that does the displaying and
13 # querying of information, and an extension to mercurial named hgk.py,
13 # querying of information, and an extension to mercurial named hgk.py,
14 # which provides hooks for hgk to get information. hgk can be found in
14 # which provides hooks for hgk to get information. hgk can be found in
15 # the contrib directory, and hgk.py can be found in the hgext
15 # the contrib directory, and hgk.py can be found in the hgext
16 # directory.
16 # directory.
17 #
17 #
18 # To load the hgext.py extension, add it to your .hgrc file (you have
18 # To load the hgext.py extension, add it to your .hgrc file (you have
19 # to use your global $HOME/.hgrc file, not one in a repository). You
19 # to use your global $HOME/.hgrc file, not one in a repository). You
20 # can specify an absolute path:
20 # can specify an absolute path:
21 #
21 #
22 # [extensions]
22 # [extensions]
23 # hgk=/usr/local/lib/hgk.py
23 # hgk=/usr/local/lib/hgk.py
24 #
24 #
25 # Mercurial can also scan the default python library path for a file
25 # Mercurial can also scan the default python library path for a file
26 # named 'hgk.py' if you set hgk empty:
26 # named 'hgk.py' if you set hgk empty:
27 #
27 #
28 # [extensions]
28 # [extensions]
29 # hgk=
29 # hgk=
30 #
30 #
31 # The hg view command will launch the hgk Tcl script. For this command
31 # The hg view command will launch the hgk Tcl script. For this command
32 # to work, hgk must be in your search path. Alternately, you can
32 # to work, hgk must be in your search path. Alternately, you can
33 # specify the path to hgk in your .hgrc file:
33 # specify the path to hgk in your .hgrc file:
34 #
34 #
35 # [hgk]
35 # [hgk]
36 # path=/location/of/hgk
36 # path=/location/of/hgk
37 #
37 #
38 # hgk can make use of the extdiff extension to visualize
38 # hgk can make use of the extdiff extension to visualize
39 # revisions. Assuming you had already configured extdiff vdiff
39 # revisions. Assuming you had already configured extdiff vdiff
40 # command, just add:
40 # command, just add:
41 #
41 #
42 # [hgk]
42 # [hgk]
43 # vdiff=vdiff
43 # vdiff=vdiff
44 #
44 #
45 # Revisions context menu will now display additional entries to fire
45 # Revisions context menu will now display additional entries to fire
46 # vdiff on hovered and selected revisions.
46 # vdiff on hovered and selected revisions.
47
47
48 import os
48 import os
49 from mercurial import commands, util, patch, revlog, cmdutil
49 from mercurial import commands, util, patch, revlog, cmdutil
50 from mercurial.node import nullid, nullrev, short
50 from mercurial.node import nullid, nullrev, short
51
51
52 def difftree(ui, repo, node1=None, node2=None, *files, **opts):
52 def difftree(ui, repo, node1=None, node2=None, *files, **opts):
53 """diff trees from two commits"""
53 """diff trees from two commits"""
54 def __difftree(repo, node1, node2, files=[]):
54 def __difftree(repo, node1, node2, files=[]):
55 assert node2 is not None
55 assert node2 is not None
56 mmap = repo.changectx(node1).manifest()
56 mmap = repo.changectx(node1).manifest()
57 mmap2 = repo.changectx(node2).manifest()
57 mmap2 = repo.changectx(node2).manifest()
58 m = cmdutil.matchfiles(repo, files)
58 m = cmdutil.matchfiles(repo, files)
59 status = repo.status(node1, node2, files=m.files(), match=m)[:5]
59 status = repo.status(node1, node2, files=m.files(), match=m)[:5]
60 modified, added, removed, deleted, unknown = status
60 modified, added, removed, deleted, unknown = status
61
61
62 empty = short(nullid)
62 empty = short(nullid)
63
63
64 for f in modified:
64 for f in modified:
65 # TODO get file permissions
65 # TODO get file permissions
66 ui.write(":100664 100664 %s %s M\t%s\t%s\n" %
66 ui.write(":100664 100664 %s %s M\t%s\t%s\n" %
67 (short(mmap[f]), short(mmap2[f]), f, f))
67 (short(mmap[f]), short(mmap2[f]), f, f))
68 for f in added:
68 for f in added:
69 ui.write(":000000 100664 %s %s N\t%s\t%s\n" %
69 ui.write(":000000 100664 %s %s N\t%s\t%s\n" %
70 (empty, short(mmap2[f]), f, f))
70 (empty, short(mmap2[f]), f, f))
71 for f in removed:
71 for f in removed:
72 ui.write(":100664 000000 %s %s D\t%s\t%s\n" %
72 ui.write(":100664 000000 %s %s D\t%s\t%s\n" %
73 (short(mmap[f]), empty, f, f))
73 (short(mmap[f]), empty, f, f))
74 ##
74 ##
75
75
76 while True:
76 while True:
77 if opts['stdin']:
77 if opts['stdin']:
78 try:
78 try:
79 line = raw_input().split(' ')
79 line = raw_input().split(' ')
80 node1 = line[0]
80 node1 = line[0]
81 if len(line) > 1:
81 if len(line) > 1:
82 node2 = line[1]
82 node2 = line[1]
83 else:
83 else:
84 node2 = None
84 node2 = None
85 except EOFError:
85 except EOFError:
86 break
86 break
87 node1 = repo.lookup(node1)
87 node1 = repo.lookup(node1)
88 if node2:
88 if node2:
89 node2 = repo.lookup(node2)
89 node2 = repo.lookup(node2)
90 else:
90 else:
91 node2 = node1
91 node2 = node1
92 node1 = repo.changelog.parents(node1)[0]
92 node1 = repo.changelog.parents(node1)[0]
93 if opts['patch']:
93 if opts['patch']:
94 if opts['pretty']:
94 if opts['pretty']:
95 catcommit(ui, repo, node2, "")
95 catcommit(ui, repo, node2, "")
96 patch.diff(repo, node1, node2,
96 m = cmdutil.matchfiles(repo, files)
97 files=files,
97 patch.diff(repo, node1, node2, files=m.files(), match=m,
98 opts=patch.diffopts(ui, {'git': True}))
98 opts=patch.diffopts(ui, {'git': True}))
99 else:
99 else:
100 __difftree(repo, node1, node2, files=files)
100 __difftree(repo, node1, node2, files=files)
101 if not opts['stdin']:
101 if not opts['stdin']:
102 break
102 break
103
103
104 def catcommit(ui, repo, n, prefix, ctx=None):
104 def catcommit(ui, repo, n, prefix, ctx=None):
105 nlprefix = '\n' + prefix;
105 nlprefix = '\n' + prefix;
106 if ctx is None:
106 if ctx is None:
107 ctx = repo.changectx(n)
107 ctx = repo.changectx(n)
108 (p1, p2) = ctx.parents()
108 (p1, p2) = ctx.parents()
109 ui.write("tree %s\n" % short(ctx.changeset()[0])) # use ctx.node() instead ??
109 ui.write("tree %s\n" % short(ctx.changeset()[0])) # use ctx.node() instead ??
110 if p1: ui.write("parent %s\n" % short(p1.node()))
110 if p1: ui.write("parent %s\n" % short(p1.node()))
111 if p2: ui.write("parent %s\n" % short(p2.node()))
111 if p2: ui.write("parent %s\n" % short(p2.node()))
112 date = ctx.date()
112 date = ctx.date()
113 description = ctx.description().replace("\0", "")
113 description = ctx.description().replace("\0", "")
114 lines = description.splitlines()
114 lines = description.splitlines()
115 if lines and lines[-1].startswith('committer:'):
115 if lines and lines[-1].startswith('committer:'):
116 committer = lines[-1].split(': ')[1].rstrip()
116 committer = lines[-1].split(': ')[1].rstrip()
117 else:
117 else:
118 committer = ctx.user()
118 committer = ctx.user()
119
119
120 ui.write("author %s %s %s\n" % (ctx.user(), int(date[0]), date[1]))
120 ui.write("author %s %s %s\n" % (ctx.user(), int(date[0]), date[1]))
121 ui.write("committer %s %s %s\n" % (committer, int(date[0]), date[1]))
121 ui.write("committer %s %s %s\n" % (committer, int(date[0]), date[1]))
122 ui.write("revision %d\n" % ctx.rev())
122 ui.write("revision %d\n" % ctx.rev())
123 ui.write("branch %s\n\n" % ctx.branch())
123 ui.write("branch %s\n\n" % ctx.branch())
124
124
125 if prefix != "":
125 if prefix != "":
126 ui.write("%s%s\n" % (prefix, description.replace('\n', nlprefix).strip()))
126 ui.write("%s%s\n" % (prefix, description.replace('\n', nlprefix).strip()))
127 else:
127 else:
128 ui.write(description + "\n")
128 ui.write(description + "\n")
129 if prefix:
129 if prefix:
130 ui.write('\0')
130 ui.write('\0')
131
131
132 def base(ui, repo, node1, node2):
132 def base(ui, repo, node1, node2):
133 """Output common ancestor information"""
133 """Output common ancestor information"""
134 node1 = repo.lookup(node1)
134 node1 = repo.lookup(node1)
135 node2 = repo.lookup(node2)
135 node2 = repo.lookup(node2)
136 n = repo.changelog.ancestor(node1, node2)
136 n = repo.changelog.ancestor(node1, node2)
137 ui.write(short(n) + "\n")
137 ui.write(short(n) + "\n")
138
138
139 def catfile(ui, repo, type=None, r=None, **opts):
139 def catfile(ui, repo, type=None, r=None, **opts):
140 """cat a specific revision"""
140 """cat a specific revision"""
141 # in stdin mode, every line except the commit is prefixed with two
141 # in stdin mode, every line except the commit is prefixed with two
142 # spaces. This way the our caller can find the commit without magic
142 # spaces. This way the our caller can find the commit without magic
143 # strings
143 # strings
144 #
144 #
145 prefix = ""
145 prefix = ""
146 if opts['stdin']:
146 if opts['stdin']:
147 try:
147 try:
148 (type, r) = raw_input().split(' ');
148 (type, r) = raw_input().split(' ');
149 prefix = " "
149 prefix = " "
150 except EOFError:
150 except EOFError:
151 return
151 return
152
152
153 else:
153 else:
154 if not type or not r:
154 if not type or not r:
155 ui.warn("cat-file: type or revision not supplied\n")
155 ui.warn("cat-file: type or revision not supplied\n")
156 commands.help_(ui, 'cat-file')
156 commands.help_(ui, 'cat-file')
157
157
158 while r:
158 while r:
159 if type != "commit":
159 if type != "commit":
160 ui.warn("aborting hg cat-file only understands commits\n")
160 ui.warn("aborting hg cat-file only understands commits\n")
161 return 1;
161 return 1;
162 n = repo.lookup(r)
162 n = repo.lookup(r)
163 catcommit(ui, repo, n, prefix)
163 catcommit(ui, repo, n, prefix)
164 if opts['stdin']:
164 if opts['stdin']:
165 try:
165 try:
166 (type, r) = raw_input().split(' ');
166 (type, r) = raw_input().split(' ');
167 except EOFError:
167 except EOFError:
168 break
168 break
169 else:
169 else:
170 break
170 break
171
171
172 # git rev-tree is a confusing thing. You can supply a number of
172 # git rev-tree is a confusing thing. You can supply a number of
173 # commit sha1s on the command line, and it walks the commit history
173 # commit sha1s on the command line, and it walks the commit history
174 # telling you which commits are reachable from the supplied ones via
174 # telling you which commits are reachable from the supplied ones via
175 # a bitmask based on arg position.
175 # a bitmask based on arg position.
176 # you can specify a commit to stop at by starting the sha1 with ^
176 # you can specify a commit to stop at by starting the sha1 with ^
177 def revtree(ui, args, repo, full="tree", maxnr=0, parents=False):
177 def revtree(ui, args, repo, full="tree", maxnr=0, parents=False):
178 def chlogwalk():
178 def chlogwalk():
179 count = repo.changelog.count()
179 count = repo.changelog.count()
180 i = count
180 i = count
181 l = [0] * 100
181 l = [0] * 100
182 chunk = 100
182 chunk = 100
183 while True:
183 while True:
184 if chunk > i:
184 if chunk > i:
185 chunk = i
185 chunk = i
186 i = 0
186 i = 0
187 else:
187 else:
188 i -= chunk
188 i -= chunk
189
189
190 for x in xrange(0, chunk):
190 for x in xrange(0, chunk):
191 if i + x >= count:
191 if i + x >= count:
192 l[chunk - x:] = [0] * (chunk - x)
192 l[chunk - x:] = [0] * (chunk - x)
193 break
193 break
194 if full != None:
194 if full != None:
195 l[x] = repo.changectx(i + x)
195 l[x] = repo.changectx(i + x)
196 l[x].changeset() # force reading
196 l[x].changeset() # force reading
197 else:
197 else:
198 l[x] = 1
198 l[x] = 1
199 for x in xrange(chunk-1, -1, -1):
199 for x in xrange(chunk-1, -1, -1):
200 if l[x] != 0:
200 if l[x] != 0:
201 yield (i + x, full != None and l[x] or None)
201 yield (i + x, full != None and l[x] or None)
202 if i == 0:
202 if i == 0:
203 break
203 break
204
204
205 # calculate and return the reachability bitmask for sha
205 # calculate and return the reachability bitmask for sha
206 def is_reachable(ar, reachable, sha):
206 def is_reachable(ar, reachable, sha):
207 if len(ar) == 0:
207 if len(ar) == 0:
208 return 1
208 return 1
209 mask = 0
209 mask = 0
210 for i in xrange(len(ar)):
210 for i in xrange(len(ar)):
211 if sha in reachable[i]:
211 if sha in reachable[i]:
212 mask |= 1 << i
212 mask |= 1 << i
213
213
214 return mask
214 return mask
215
215
216 reachable = []
216 reachable = []
217 stop_sha1 = []
217 stop_sha1 = []
218 want_sha1 = []
218 want_sha1 = []
219 count = 0
219 count = 0
220
220
221 # figure out which commits they are asking for and which ones they
221 # figure out which commits they are asking for and which ones they
222 # want us to stop on
222 # want us to stop on
223 for i in xrange(len(args)):
223 for i in xrange(len(args)):
224 if args[i].startswith('^'):
224 if args[i].startswith('^'):
225 s = repo.lookup(args[i][1:])
225 s = repo.lookup(args[i][1:])
226 stop_sha1.append(s)
226 stop_sha1.append(s)
227 want_sha1.append(s)
227 want_sha1.append(s)
228 elif args[i] != 'HEAD':
228 elif args[i] != 'HEAD':
229 want_sha1.append(repo.lookup(args[i]))
229 want_sha1.append(repo.lookup(args[i]))
230
230
231 # calculate the graph for the supplied commits
231 # calculate the graph for the supplied commits
232 for i in xrange(len(want_sha1)):
232 for i in xrange(len(want_sha1)):
233 reachable.append({});
233 reachable.append({});
234 n = want_sha1[i];
234 n = want_sha1[i];
235 visit = [n];
235 visit = [n];
236 reachable[i][n] = 1
236 reachable[i][n] = 1
237 while visit:
237 while visit:
238 n = visit.pop(0)
238 n = visit.pop(0)
239 if n in stop_sha1:
239 if n in stop_sha1:
240 continue
240 continue
241 for p in repo.changelog.parents(n):
241 for p in repo.changelog.parents(n):
242 if p not in reachable[i]:
242 if p not in reachable[i]:
243 reachable[i][p] = 1
243 reachable[i][p] = 1
244 visit.append(p)
244 visit.append(p)
245 if p in stop_sha1:
245 if p in stop_sha1:
246 continue
246 continue
247
247
248 # walk the repository looking for commits that are in our
248 # walk the repository looking for commits that are in our
249 # reachability graph
249 # reachability graph
250 for i, ctx in chlogwalk():
250 for i, ctx in chlogwalk():
251 n = repo.changelog.node(i)
251 n = repo.changelog.node(i)
252 mask = is_reachable(want_sha1, reachable, n)
252 mask = is_reachable(want_sha1, reachable, n)
253 if mask:
253 if mask:
254 parentstr = ""
254 parentstr = ""
255 if parents:
255 if parents:
256 pp = repo.changelog.parents(n)
256 pp = repo.changelog.parents(n)
257 if pp[0] != nullid:
257 if pp[0] != nullid:
258 parentstr += " " + short(pp[0])
258 parentstr += " " + short(pp[0])
259 if pp[1] != nullid:
259 if pp[1] != nullid:
260 parentstr += " " + short(pp[1])
260 parentstr += " " + short(pp[1])
261 if not full:
261 if not full:
262 ui.write("%s%s\n" % (short(n), parentstr))
262 ui.write("%s%s\n" % (short(n), parentstr))
263 elif full == "commit":
263 elif full == "commit":
264 ui.write("%s%s\n" % (short(n), parentstr))
264 ui.write("%s%s\n" % (short(n), parentstr))
265 catcommit(ui, repo, n, ' ', ctx)
265 catcommit(ui, repo, n, ' ', ctx)
266 else:
266 else:
267 (p1, p2) = repo.changelog.parents(n)
267 (p1, p2) = repo.changelog.parents(n)
268 (h, h1, h2) = map(short, (n, p1, p2))
268 (h, h1, h2) = map(short, (n, p1, p2))
269 (i1, i2) = map(repo.changelog.rev, (p1, p2))
269 (i1, i2) = map(repo.changelog.rev, (p1, p2))
270
270
271 date = ctx.date()[0]
271 date = ctx.date()[0]
272 ui.write("%s %s:%s" % (date, h, mask))
272 ui.write("%s %s:%s" % (date, h, mask))
273 mask = is_reachable(want_sha1, reachable, p1)
273 mask = is_reachable(want_sha1, reachable, p1)
274 if i1 != nullrev and mask > 0:
274 if i1 != nullrev and mask > 0:
275 ui.write("%s:%s " % (h1, mask)),
275 ui.write("%s:%s " % (h1, mask)),
276 mask = is_reachable(want_sha1, reachable, p2)
276 mask = is_reachable(want_sha1, reachable, p2)
277 if i2 != nullrev and mask > 0:
277 if i2 != nullrev and mask > 0:
278 ui.write("%s:%s " % (h2, mask))
278 ui.write("%s:%s " % (h2, mask))
279 ui.write("\n")
279 ui.write("\n")
280 if maxnr and count >= maxnr:
280 if maxnr and count >= maxnr:
281 break
281 break
282 count += 1
282 count += 1
283
283
284 def revparse(ui, repo, *revs, **opts):
284 def revparse(ui, repo, *revs, **opts):
285 """Parse given revisions"""
285 """Parse given revisions"""
286 def revstr(rev):
286 def revstr(rev):
287 if rev == 'HEAD':
287 if rev == 'HEAD':
288 rev = 'tip'
288 rev = 'tip'
289 return revlog.hex(repo.lookup(rev))
289 return revlog.hex(repo.lookup(rev))
290
290
291 for r in revs:
291 for r in revs:
292 revrange = r.split(':', 1)
292 revrange = r.split(':', 1)
293 ui.write('%s\n' % revstr(revrange[0]))
293 ui.write('%s\n' % revstr(revrange[0]))
294 if len(revrange) == 2:
294 if len(revrange) == 2:
295 ui.write('^%s\n' % revstr(revrange[1]))
295 ui.write('^%s\n' % revstr(revrange[1]))
296
296
297 # git rev-list tries to order things by date, and has the ability to stop
297 # git rev-list tries to order things by date, and has the ability to stop
298 # at a given commit without walking the whole repo. TODO add the stop
298 # at a given commit without walking the whole repo. TODO add the stop
299 # parameter
299 # parameter
300 def revlist(ui, repo, *revs, **opts):
300 def revlist(ui, repo, *revs, **opts):
301 """print revisions"""
301 """print revisions"""
302 if opts['header']:
302 if opts['header']:
303 full = "commit"
303 full = "commit"
304 else:
304 else:
305 full = None
305 full = None
306 copy = [x for x in revs]
306 copy = [x for x in revs]
307 revtree(ui, copy, repo, full, opts['max_count'], opts['parents'])
307 revtree(ui, copy, repo, full, opts['max_count'], opts['parents'])
308
308
309 def config(ui, repo, **opts):
309 def config(ui, repo, **opts):
310 """print extension options"""
310 """print extension options"""
311 def writeopt(name, value):
311 def writeopt(name, value):
312 ui.write('k=%s\nv=%s\n' % (name, value))
312 ui.write('k=%s\nv=%s\n' % (name, value))
313
313
314 writeopt('vdiff', ui.config('hgk', 'vdiff', ''))
314 writeopt('vdiff', ui.config('hgk', 'vdiff', ''))
315
315
316
316
317 def view(ui, repo, *etc, **opts):
317 def view(ui, repo, *etc, **opts):
318 "start interactive history viewer"
318 "start interactive history viewer"
319 os.chdir(repo.root)
319 os.chdir(repo.root)
320 optstr = ' '.join(['--%s %s' % (k, v) for k, v in opts.iteritems() if v])
320 optstr = ' '.join(['--%s %s' % (k, v) for k, v in opts.iteritems() if v])
321 cmd = ui.config("hgk", "path", "hgk") + " %s %s" % (optstr, " ".join(etc))
321 cmd = ui.config("hgk", "path", "hgk") + " %s %s" % (optstr, " ".join(etc))
322 ui.debug("running %s\n" % cmd)
322 ui.debug("running %s\n" % cmd)
323 util.system(cmd)
323 util.system(cmd)
324
324
325 cmdtable = {
325 cmdtable = {
326 "^view":
326 "^view":
327 (view,
327 (view,
328 [('l', 'limit', '', 'limit number of changes displayed')],
328 [('l', 'limit', '', 'limit number of changes displayed')],
329 'hg view [-l LIMIT] [REVRANGE]'),
329 'hg view [-l LIMIT] [REVRANGE]'),
330 "debug-diff-tree":
330 "debug-diff-tree":
331 (difftree,
331 (difftree,
332 [('p', 'patch', None, 'generate patch'),
332 [('p', 'patch', None, 'generate patch'),
333 ('r', 'recursive', None, 'recursive'),
333 ('r', 'recursive', None, 'recursive'),
334 ('P', 'pretty', None, 'pretty'),
334 ('P', 'pretty', None, 'pretty'),
335 ('s', 'stdin', None, 'stdin'),
335 ('s', 'stdin', None, 'stdin'),
336 ('C', 'copy', None, 'detect copies'),
336 ('C', 'copy', None, 'detect copies'),
337 ('S', 'search', "", 'search')],
337 ('S', 'search', "", 'search')],
338 'hg git-diff-tree [OPTION]... NODE1 NODE2 [FILE]...'),
338 'hg git-diff-tree [OPTION]... NODE1 NODE2 [FILE]...'),
339 "debug-cat-file":
339 "debug-cat-file":
340 (catfile,
340 (catfile,
341 [('s', 'stdin', None, 'stdin')],
341 [('s', 'stdin', None, 'stdin')],
342 'hg debug-cat-file [OPTION]... TYPE FILE'),
342 'hg debug-cat-file [OPTION]... TYPE FILE'),
343 "debug-config":
343 "debug-config":
344 (config, [], 'hg debug-config'),
344 (config, [], 'hg debug-config'),
345 "debug-merge-base":
345 "debug-merge-base":
346 (base, [], 'hg debug-merge-base node node'),
346 (base, [], 'hg debug-merge-base node node'),
347 "debug-rev-parse":
347 "debug-rev-parse":
348 (revparse,
348 (revparse,
349 [('', 'default', '', 'ignored')],
349 [('', 'default', '', 'ignored')],
350 'hg debug-rev-parse REV'),
350 'hg debug-rev-parse REV'),
351 "debug-rev-list":
351 "debug-rev-list":
352 (revlist,
352 (revlist,
353 [('H', 'header', None, 'header'),
353 [('H', 'header', None, 'header'),
354 ('t', 'topo-order', None, 'topo-order'),
354 ('t', 'topo-order', None, 'topo-order'),
355 ('p', 'parents', None, 'parents'),
355 ('p', 'parents', None, 'parents'),
356 ('n', 'max-count', 0, 'max-count')],
356 ('n', 'max-count', 0, 'max-count')],
357 'hg debug-rev-list [options] revs'),
357 'hg debug-rev-list [options] revs'),
358 }
358 }
@@ -1,2364 +1,2364 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
5 # This software may be used and distributed according to the terms
6 # of the GNU General Public License, incorporated herein by reference.
6 # of the GNU General Public License, incorporated herein by reference.
7
7
8 '''patch management and development
8 '''patch management and development
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 prepare repository to work with patches qinit
19 prepare repository to work with patches qinit
20 create new patch qnew
20 create new patch qnew
21 import existing patch qimport
21 import existing patch qimport
22
22
23 print patch series qseries
23 print patch series qseries
24 print applied patches qapplied
24 print applied patches qapplied
25 print name of top applied patch qtop
25 print name of top applied patch qtop
26
26
27 add known patch to applied stack qpush
27 add known patch to applied stack qpush
28 remove patch from applied stack qpop
28 remove patch from applied stack qpop
29 refresh contents of top applied patch qrefresh
29 refresh contents of top applied patch qrefresh
30 '''
30 '''
31
31
32 from mercurial.i18n import _
32 from mercurial.i18n import _
33 from mercurial.node import bin, hex, short
33 from mercurial.node import bin, hex, short
34 from mercurial.repo import RepoError
34 from mercurial.repo import RepoError
35 from mercurial import commands, cmdutil, hg, patch, revlog, util
35 from mercurial import commands, cmdutil, hg, patch, revlog, util
36 from mercurial import repair
36 from mercurial import repair
37 import os, sys, re, errno
37 import os, sys, re, errno
38
38
39 commands.norepo += " qclone"
39 commands.norepo += " qclone"
40
40
41 # Patch names looks like unix-file names.
41 # Patch names looks like unix-file names.
42 # They must be joinable with queue directory and result in the patch path.
42 # They must be joinable with queue directory and result in the patch path.
43 normname = util.normpath
43 normname = util.normpath
44
44
45 class statusentry:
45 class statusentry:
46 def __init__(self, rev, name=None):
46 def __init__(self, rev, name=None):
47 if not name:
47 if not name:
48 fields = rev.split(':', 1)
48 fields = rev.split(':', 1)
49 if len(fields) == 2:
49 if len(fields) == 2:
50 self.rev, self.name = fields
50 self.rev, self.name = fields
51 else:
51 else:
52 self.rev, self.name = None, None
52 self.rev, self.name = None, None
53 else:
53 else:
54 self.rev, self.name = rev, name
54 self.rev, self.name = rev, name
55
55
56 def __str__(self):
56 def __str__(self):
57 return self.rev + ':' + self.name
57 return self.rev + ':' + self.name
58
58
59 class queue:
59 class queue:
60 def __init__(self, ui, path, patchdir=None):
60 def __init__(self, ui, path, patchdir=None):
61 self.basepath = path
61 self.basepath = path
62 self.path = patchdir or os.path.join(path, "patches")
62 self.path = patchdir or os.path.join(path, "patches")
63 self.opener = util.opener(self.path)
63 self.opener = util.opener(self.path)
64 self.ui = ui
64 self.ui = ui
65 self.applied = []
65 self.applied = []
66 self.full_series = []
66 self.full_series = []
67 self.applied_dirty = 0
67 self.applied_dirty = 0
68 self.series_dirty = 0
68 self.series_dirty = 0
69 self.series_path = "series"
69 self.series_path = "series"
70 self.status_path = "status"
70 self.status_path = "status"
71 self.guards_path = "guards"
71 self.guards_path = "guards"
72 self.active_guards = None
72 self.active_guards = None
73 self.guards_dirty = False
73 self.guards_dirty = False
74 self._diffopts = None
74 self._diffopts = None
75
75
76 if os.path.exists(self.join(self.series_path)):
76 if os.path.exists(self.join(self.series_path)):
77 self.full_series = self.opener(self.series_path).read().splitlines()
77 self.full_series = self.opener(self.series_path).read().splitlines()
78 self.parse_series()
78 self.parse_series()
79
79
80 if os.path.exists(self.join(self.status_path)):
80 if os.path.exists(self.join(self.status_path)):
81 lines = self.opener(self.status_path).read().splitlines()
81 lines = self.opener(self.status_path).read().splitlines()
82 self.applied = [statusentry(l) for l in lines]
82 self.applied = [statusentry(l) for l in lines]
83
83
84 def diffopts(self):
84 def diffopts(self):
85 if self._diffopts is None:
85 if self._diffopts is None:
86 self._diffopts = patch.diffopts(self.ui)
86 self._diffopts = patch.diffopts(self.ui)
87 return self._diffopts
87 return self._diffopts
88
88
89 def join(self, *p):
89 def join(self, *p):
90 return os.path.join(self.path, *p)
90 return os.path.join(self.path, *p)
91
91
92 def find_series(self, patch):
92 def find_series(self, patch):
93 pre = re.compile("(\s*)([^#]+)")
93 pre = re.compile("(\s*)([^#]+)")
94 index = 0
94 index = 0
95 for l in self.full_series:
95 for l in self.full_series:
96 m = pre.match(l)
96 m = pre.match(l)
97 if m:
97 if m:
98 s = m.group(2)
98 s = m.group(2)
99 s = s.rstrip()
99 s = s.rstrip()
100 if s == patch:
100 if s == patch:
101 return index
101 return index
102 index += 1
102 index += 1
103 return None
103 return None
104
104
105 guard_re = re.compile(r'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
105 guard_re = re.compile(r'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
106
106
107 def parse_series(self):
107 def parse_series(self):
108 self.series = []
108 self.series = []
109 self.series_guards = []
109 self.series_guards = []
110 for l in self.full_series:
110 for l in self.full_series:
111 h = l.find('#')
111 h = l.find('#')
112 if h == -1:
112 if h == -1:
113 patch = l
113 patch = l
114 comment = ''
114 comment = ''
115 elif h == 0:
115 elif h == 0:
116 continue
116 continue
117 else:
117 else:
118 patch = l[:h]
118 patch = l[:h]
119 comment = l[h:]
119 comment = l[h:]
120 patch = patch.strip()
120 patch = patch.strip()
121 if patch:
121 if patch:
122 if patch in self.series:
122 if patch in self.series:
123 raise util.Abort(_('%s appears more than once in %s') %
123 raise util.Abort(_('%s appears more than once in %s') %
124 (patch, self.join(self.series_path)))
124 (patch, self.join(self.series_path)))
125 self.series.append(patch)
125 self.series.append(patch)
126 self.series_guards.append(self.guard_re.findall(comment))
126 self.series_guards.append(self.guard_re.findall(comment))
127
127
128 def check_guard(self, guard):
128 def check_guard(self, guard):
129 bad_chars = '# \t\r\n\f'
129 bad_chars = '# \t\r\n\f'
130 first = guard[0]
130 first = guard[0]
131 for c in '-+':
131 for c in '-+':
132 if first == c:
132 if first == c:
133 return (_('guard %r starts with invalid character: %r') %
133 return (_('guard %r starts with invalid character: %r') %
134 (guard, c))
134 (guard, c))
135 for c in bad_chars:
135 for c in bad_chars:
136 if c in guard:
136 if c in guard:
137 return _('invalid character in guard %r: %r') % (guard, c)
137 return _('invalid character in guard %r: %r') % (guard, c)
138
138
139 def set_active(self, guards):
139 def set_active(self, guards):
140 for guard in guards:
140 for guard in guards:
141 bad = self.check_guard(guard)
141 bad = self.check_guard(guard)
142 if bad:
142 if bad:
143 raise util.Abort(bad)
143 raise util.Abort(bad)
144 guards = dict.fromkeys(guards).keys()
144 guards = dict.fromkeys(guards).keys()
145 guards.sort()
145 guards.sort()
146 self.ui.debug('active guards: %s\n' % ' '.join(guards))
146 self.ui.debug('active guards: %s\n' % ' '.join(guards))
147 self.active_guards = guards
147 self.active_guards = guards
148 self.guards_dirty = True
148 self.guards_dirty = True
149
149
150 def active(self):
150 def active(self):
151 if self.active_guards is None:
151 if self.active_guards is None:
152 self.active_guards = []
152 self.active_guards = []
153 try:
153 try:
154 guards = self.opener(self.guards_path).read().split()
154 guards = self.opener(self.guards_path).read().split()
155 except IOError, err:
155 except IOError, err:
156 if err.errno != errno.ENOENT: raise
156 if err.errno != errno.ENOENT: raise
157 guards = []
157 guards = []
158 for i, guard in enumerate(guards):
158 for i, guard in enumerate(guards):
159 bad = self.check_guard(guard)
159 bad = self.check_guard(guard)
160 if bad:
160 if bad:
161 self.ui.warn('%s:%d: %s\n' %
161 self.ui.warn('%s:%d: %s\n' %
162 (self.join(self.guards_path), i + 1, bad))
162 (self.join(self.guards_path), i + 1, bad))
163 else:
163 else:
164 self.active_guards.append(guard)
164 self.active_guards.append(guard)
165 return self.active_guards
165 return self.active_guards
166
166
167 def set_guards(self, idx, guards):
167 def set_guards(self, idx, guards):
168 for g in guards:
168 for g in guards:
169 if len(g) < 2:
169 if len(g) < 2:
170 raise util.Abort(_('guard %r too short') % g)
170 raise util.Abort(_('guard %r too short') % g)
171 if g[0] not in '-+':
171 if g[0] not in '-+':
172 raise util.Abort(_('guard %r starts with invalid char') % g)
172 raise util.Abort(_('guard %r starts with invalid char') % g)
173 bad = self.check_guard(g[1:])
173 bad = self.check_guard(g[1:])
174 if bad:
174 if bad:
175 raise util.Abort(bad)
175 raise util.Abort(bad)
176 drop = self.guard_re.sub('', self.full_series[idx])
176 drop = self.guard_re.sub('', self.full_series[idx])
177 self.full_series[idx] = drop + ''.join([' #' + g for g in guards])
177 self.full_series[idx] = drop + ''.join([' #' + g for g in guards])
178 self.parse_series()
178 self.parse_series()
179 self.series_dirty = True
179 self.series_dirty = True
180
180
181 def pushable(self, idx):
181 def pushable(self, idx):
182 if isinstance(idx, str):
182 if isinstance(idx, str):
183 idx = self.series.index(idx)
183 idx = self.series.index(idx)
184 patchguards = self.series_guards[idx]
184 patchguards = self.series_guards[idx]
185 if not patchguards:
185 if not patchguards:
186 return True, None
186 return True, None
187 default = False
187 default = False
188 guards = self.active()
188 guards = self.active()
189 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
189 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
190 if exactneg:
190 if exactneg:
191 return False, exactneg[0]
191 return False, exactneg[0]
192 pos = [g for g in patchguards if g[0] == '+']
192 pos = [g for g in patchguards if g[0] == '+']
193 exactpos = [g for g in pos if g[1:] in guards]
193 exactpos = [g for g in pos if g[1:] in guards]
194 if pos:
194 if pos:
195 if exactpos:
195 if exactpos:
196 return True, exactpos[0]
196 return True, exactpos[0]
197 return False, pos
197 return False, pos
198 return True, ''
198 return True, ''
199
199
200 def explain_pushable(self, idx, all_patches=False):
200 def explain_pushable(self, idx, all_patches=False):
201 write = all_patches and self.ui.write or self.ui.warn
201 write = all_patches and self.ui.write or self.ui.warn
202 if all_patches or self.ui.verbose:
202 if all_patches or self.ui.verbose:
203 if isinstance(idx, str):
203 if isinstance(idx, str):
204 idx = self.series.index(idx)
204 idx = self.series.index(idx)
205 pushable, why = self.pushable(idx)
205 pushable, why = self.pushable(idx)
206 if all_patches and pushable:
206 if all_patches and pushable:
207 if why is None:
207 if why is None:
208 write(_('allowing %s - no guards in effect\n') %
208 write(_('allowing %s - no guards in effect\n') %
209 self.series[idx])
209 self.series[idx])
210 else:
210 else:
211 if not why:
211 if not why:
212 write(_('allowing %s - no matching negative guards\n') %
212 write(_('allowing %s - no matching negative guards\n') %
213 self.series[idx])
213 self.series[idx])
214 else:
214 else:
215 write(_('allowing %s - guarded by %r\n') %
215 write(_('allowing %s - guarded by %r\n') %
216 (self.series[idx], why))
216 (self.series[idx], why))
217 if not pushable:
217 if not pushable:
218 if why:
218 if why:
219 write(_('skipping %s - guarded by %r\n') %
219 write(_('skipping %s - guarded by %r\n') %
220 (self.series[idx], why))
220 (self.series[idx], why))
221 else:
221 else:
222 write(_('skipping %s - no matching guards\n') %
222 write(_('skipping %s - no matching guards\n') %
223 self.series[idx])
223 self.series[idx])
224
224
225 def save_dirty(self):
225 def save_dirty(self):
226 def write_list(items, path):
226 def write_list(items, path):
227 fp = self.opener(path, 'w')
227 fp = self.opener(path, 'w')
228 for i in items:
228 for i in items:
229 fp.write("%s\n" % i)
229 fp.write("%s\n" % i)
230 fp.close()
230 fp.close()
231 if self.applied_dirty: write_list(map(str, self.applied), self.status_path)
231 if self.applied_dirty: write_list(map(str, self.applied), self.status_path)
232 if self.series_dirty: write_list(self.full_series, self.series_path)
232 if self.series_dirty: write_list(self.full_series, self.series_path)
233 if self.guards_dirty: write_list(self.active_guards, self.guards_path)
233 if self.guards_dirty: write_list(self.active_guards, self.guards_path)
234
234
235 def readheaders(self, patch):
235 def readheaders(self, patch):
236 def eatdiff(lines):
236 def eatdiff(lines):
237 while lines:
237 while lines:
238 l = lines[-1]
238 l = lines[-1]
239 if (l.startswith("diff -") or
239 if (l.startswith("diff -") or
240 l.startswith("Index:") or
240 l.startswith("Index:") or
241 l.startswith("===========")):
241 l.startswith("===========")):
242 del lines[-1]
242 del lines[-1]
243 else:
243 else:
244 break
244 break
245 def eatempty(lines):
245 def eatempty(lines):
246 while lines:
246 while lines:
247 l = lines[-1]
247 l = lines[-1]
248 if re.match('\s*$', l):
248 if re.match('\s*$', l):
249 del lines[-1]
249 del lines[-1]
250 else:
250 else:
251 break
251 break
252
252
253 pf = self.join(patch)
253 pf = self.join(patch)
254 message = []
254 message = []
255 comments = []
255 comments = []
256 user = None
256 user = None
257 date = None
257 date = None
258 format = None
258 format = None
259 subject = None
259 subject = None
260 diffstart = 0
260 diffstart = 0
261
261
262 for line in file(pf):
262 for line in file(pf):
263 line = line.rstrip()
263 line = line.rstrip()
264 if line.startswith('diff --git'):
264 if line.startswith('diff --git'):
265 diffstart = 2
265 diffstart = 2
266 break
266 break
267 if diffstart:
267 if diffstart:
268 if line.startswith('+++ '):
268 if line.startswith('+++ '):
269 diffstart = 2
269 diffstart = 2
270 break
270 break
271 if line.startswith("--- "):
271 if line.startswith("--- "):
272 diffstart = 1
272 diffstart = 1
273 continue
273 continue
274 elif format == "hgpatch":
274 elif format == "hgpatch":
275 # parse values when importing the result of an hg export
275 # parse values when importing the result of an hg export
276 if line.startswith("# User "):
276 if line.startswith("# User "):
277 user = line[7:]
277 user = line[7:]
278 elif line.startswith("# Date "):
278 elif line.startswith("# Date "):
279 date = line[7:]
279 date = line[7:]
280 elif not line.startswith("# ") and line:
280 elif not line.startswith("# ") and line:
281 message.append(line)
281 message.append(line)
282 format = None
282 format = None
283 elif line == '# HG changeset patch':
283 elif line == '# HG changeset patch':
284 format = "hgpatch"
284 format = "hgpatch"
285 elif (format != "tagdone" and (line.startswith("Subject: ") or
285 elif (format != "tagdone" and (line.startswith("Subject: ") or
286 line.startswith("subject: "))):
286 line.startswith("subject: "))):
287 subject = line[9:]
287 subject = line[9:]
288 format = "tag"
288 format = "tag"
289 elif (format != "tagdone" and (line.startswith("From: ") or
289 elif (format != "tagdone" and (line.startswith("From: ") or
290 line.startswith("from: "))):
290 line.startswith("from: "))):
291 user = line[6:]
291 user = line[6:]
292 format = "tag"
292 format = "tag"
293 elif format == "tag" and line == "":
293 elif format == "tag" and line == "":
294 # when looking for tags (subject: from: etc) they
294 # when looking for tags (subject: from: etc) they
295 # end once you find a blank line in the source
295 # end once you find a blank line in the source
296 format = "tagdone"
296 format = "tagdone"
297 elif message or line:
297 elif message or line:
298 message.append(line)
298 message.append(line)
299 comments.append(line)
299 comments.append(line)
300
300
301 eatdiff(message)
301 eatdiff(message)
302 eatdiff(comments)
302 eatdiff(comments)
303 eatempty(message)
303 eatempty(message)
304 eatempty(comments)
304 eatempty(comments)
305
305
306 # make sure message isn't empty
306 # make sure message isn't empty
307 if format and format.startswith("tag") and subject:
307 if format and format.startswith("tag") and subject:
308 message.insert(0, "")
308 message.insert(0, "")
309 message.insert(0, subject)
309 message.insert(0, subject)
310 return (message, comments, user, date, diffstart > 1)
310 return (message, comments, user, date, diffstart > 1)
311
311
312 def removeundo(self, repo):
312 def removeundo(self, repo):
313 undo = repo.sjoin('undo')
313 undo = repo.sjoin('undo')
314 if not os.path.exists(undo):
314 if not os.path.exists(undo):
315 return
315 return
316 try:
316 try:
317 os.unlink(undo)
317 os.unlink(undo)
318 except OSError, inst:
318 except OSError, inst:
319 self.ui.warn('error removing undo: %s\n' % str(inst))
319 self.ui.warn('error removing undo: %s\n' % str(inst))
320
320
321 def printdiff(self, repo, node1, node2=None, files=None,
321 def printdiff(self, repo, node1, node2=None, files=None,
322 fp=None, changes=None, opts={}):
322 fp=None, changes=None, opts={}):
323 m = cmdutil.match(repo, files, opts)
323 m = cmdutil.match(repo, files, opts)
324 patch.diff(repo, node1, node2, m.files(), match=m,
324 patch.diff(repo, node1, node2, m.files(), match=m,
325 fp=fp, changes=changes, opts=self.diffopts())
325 fp=fp, changes=changes, opts=self.diffopts())
326
326
327 def mergeone(self, repo, mergeq, head, patch, rev):
327 def mergeone(self, repo, mergeq, head, patch, rev):
328 # first try just applying the patch
328 # first try just applying the patch
329 (err, n) = self.apply(repo, [ patch ], update_status=False,
329 (err, n) = self.apply(repo, [ patch ], update_status=False,
330 strict=True, merge=rev)
330 strict=True, merge=rev)
331
331
332 if err == 0:
332 if err == 0:
333 return (err, n)
333 return (err, n)
334
334
335 if n is None:
335 if n is None:
336 raise util.Abort(_("apply failed for patch %s") % patch)
336 raise util.Abort(_("apply failed for patch %s") % patch)
337
337
338 self.ui.warn("patch didn't work out, merging %s\n" % patch)
338 self.ui.warn("patch didn't work out, merging %s\n" % patch)
339
339
340 # apply failed, strip away that rev and merge.
340 # apply failed, strip away that rev and merge.
341 hg.clean(repo, head)
341 hg.clean(repo, head)
342 self.strip(repo, n, update=False, backup='strip')
342 self.strip(repo, n, update=False, backup='strip')
343
343
344 ctx = repo.changectx(rev)
344 ctx = repo.changectx(rev)
345 ret = hg.merge(repo, rev)
345 ret = hg.merge(repo, rev)
346 if ret:
346 if ret:
347 raise util.Abort(_("update returned %d") % ret)
347 raise util.Abort(_("update returned %d") % ret)
348 n = repo.commit(None, ctx.description(), ctx.user(), force=1)
348 n = repo.commit(None, ctx.description(), ctx.user(), force=1)
349 if n == None:
349 if n == None:
350 raise util.Abort(_("repo commit failed"))
350 raise util.Abort(_("repo commit failed"))
351 try:
351 try:
352 message, comments, user, date, patchfound = mergeq.readheaders(patch)
352 message, comments, user, date, patchfound = mergeq.readheaders(patch)
353 except:
353 except:
354 raise util.Abort(_("unable to read %s") % patch)
354 raise util.Abort(_("unable to read %s") % patch)
355
355
356 patchf = self.opener(patch, "w")
356 patchf = self.opener(patch, "w")
357 if comments:
357 if comments:
358 comments = "\n".join(comments) + '\n\n'
358 comments = "\n".join(comments) + '\n\n'
359 patchf.write(comments)
359 patchf.write(comments)
360 self.printdiff(repo, head, n, fp=patchf)
360 self.printdiff(repo, head, n, fp=patchf)
361 patchf.close()
361 patchf.close()
362 self.removeundo(repo)
362 self.removeundo(repo)
363 return (0, n)
363 return (0, n)
364
364
365 def qparents(self, repo, rev=None):
365 def qparents(self, repo, rev=None):
366 if rev is None:
366 if rev is None:
367 (p1, p2) = repo.dirstate.parents()
367 (p1, p2) = repo.dirstate.parents()
368 if p2 == revlog.nullid:
368 if p2 == revlog.nullid:
369 return p1
369 return p1
370 if len(self.applied) == 0:
370 if len(self.applied) == 0:
371 return None
371 return None
372 return revlog.bin(self.applied[-1].rev)
372 return revlog.bin(self.applied[-1].rev)
373 pp = repo.changelog.parents(rev)
373 pp = repo.changelog.parents(rev)
374 if pp[1] != revlog.nullid:
374 if pp[1] != revlog.nullid:
375 arevs = [ x.rev for x in self.applied ]
375 arevs = [ x.rev for x in self.applied ]
376 p0 = revlog.hex(pp[0])
376 p0 = revlog.hex(pp[0])
377 p1 = revlog.hex(pp[1])
377 p1 = revlog.hex(pp[1])
378 if p0 in arevs:
378 if p0 in arevs:
379 return pp[0]
379 return pp[0]
380 if p1 in arevs:
380 if p1 in arevs:
381 return pp[1]
381 return pp[1]
382 return pp[0]
382 return pp[0]
383
383
384 def mergepatch(self, repo, mergeq, series):
384 def mergepatch(self, repo, mergeq, series):
385 if len(self.applied) == 0:
385 if len(self.applied) == 0:
386 # each of the patches merged in will have two parents. This
386 # each of the patches merged in will have two parents. This
387 # can confuse the qrefresh, qdiff, and strip code because it
387 # can confuse the qrefresh, qdiff, and strip code because it
388 # needs to know which parent is actually in the patch queue.
388 # needs to know which parent is actually in the patch queue.
389 # so, we insert a merge marker with only one parent. This way
389 # so, we insert a merge marker with only one parent. This way
390 # the first patch in the queue is never a merge patch
390 # the first patch in the queue is never a merge patch
391 #
391 #
392 pname = ".hg.patches.merge.marker"
392 pname = ".hg.patches.merge.marker"
393 n = repo.commit(None, '[mq]: merge marker', user=None, force=1)
393 n = repo.commit(None, '[mq]: merge marker', user=None, force=1)
394 self.removeundo(repo)
394 self.removeundo(repo)
395 self.applied.append(statusentry(revlog.hex(n), pname))
395 self.applied.append(statusentry(revlog.hex(n), pname))
396 self.applied_dirty = 1
396 self.applied_dirty = 1
397
397
398 head = self.qparents(repo)
398 head = self.qparents(repo)
399
399
400 for patch in series:
400 for patch in series:
401 patch = mergeq.lookup(patch, strict=True)
401 patch = mergeq.lookup(patch, strict=True)
402 if not patch:
402 if not patch:
403 self.ui.warn("patch %s does not exist\n" % patch)
403 self.ui.warn("patch %s does not exist\n" % patch)
404 return (1, None)
404 return (1, None)
405 pushable, reason = self.pushable(patch)
405 pushable, reason = self.pushable(patch)
406 if not pushable:
406 if not pushable:
407 self.explain_pushable(patch, all_patches=True)
407 self.explain_pushable(patch, all_patches=True)
408 continue
408 continue
409 info = mergeq.isapplied(patch)
409 info = mergeq.isapplied(patch)
410 if not info:
410 if not info:
411 self.ui.warn("patch %s is not applied\n" % patch)
411 self.ui.warn("patch %s is not applied\n" % patch)
412 return (1, None)
412 return (1, None)
413 rev = revlog.bin(info[1])
413 rev = revlog.bin(info[1])
414 (err, head) = self.mergeone(repo, mergeq, head, patch, rev)
414 (err, head) = self.mergeone(repo, mergeq, head, patch, rev)
415 if head:
415 if head:
416 self.applied.append(statusentry(revlog.hex(head), patch))
416 self.applied.append(statusentry(revlog.hex(head), patch))
417 self.applied_dirty = 1
417 self.applied_dirty = 1
418 if err:
418 if err:
419 return (err, head)
419 return (err, head)
420 self.save_dirty()
420 self.save_dirty()
421 return (0, head)
421 return (0, head)
422
422
423 def patch(self, repo, patchfile):
423 def patch(self, repo, patchfile):
424 '''Apply patchfile to the working directory.
424 '''Apply patchfile to the working directory.
425 patchfile: file name of patch'''
425 patchfile: file name of patch'''
426 files = {}
426 files = {}
427 try:
427 try:
428 fuzz = patch.patch(patchfile, self.ui, strip=1, cwd=repo.root,
428 fuzz = patch.patch(patchfile, self.ui, strip=1, cwd=repo.root,
429 files=files)
429 files=files)
430 except Exception, inst:
430 except Exception, inst:
431 self.ui.note(str(inst) + '\n')
431 self.ui.note(str(inst) + '\n')
432 if not self.ui.verbose:
432 if not self.ui.verbose:
433 self.ui.warn("patch failed, unable to continue (try -v)\n")
433 self.ui.warn("patch failed, unable to continue (try -v)\n")
434 return (False, files, False)
434 return (False, files, False)
435
435
436 return (True, files, fuzz)
436 return (True, files, fuzz)
437
437
438 def apply(self, repo, series, list=False, update_status=True,
438 def apply(self, repo, series, list=False, update_status=True,
439 strict=False, patchdir=None, merge=None, all_files={}):
439 strict=False, patchdir=None, merge=None, all_files={}):
440 wlock = lock = tr = None
440 wlock = lock = tr = None
441 try:
441 try:
442 wlock = repo.wlock()
442 wlock = repo.wlock()
443 lock = repo.lock()
443 lock = repo.lock()
444 tr = repo.transaction()
444 tr = repo.transaction()
445 try:
445 try:
446 ret = self._apply(repo, series, list, update_status,
446 ret = self._apply(repo, series, list, update_status,
447 strict, patchdir, merge, all_files=all_files)
447 strict, patchdir, merge, all_files=all_files)
448 tr.close()
448 tr.close()
449 self.save_dirty()
449 self.save_dirty()
450 return ret
450 return ret
451 except:
451 except:
452 try:
452 try:
453 tr.abort()
453 tr.abort()
454 finally:
454 finally:
455 repo.invalidate()
455 repo.invalidate()
456 repo.dirstate.invalidate()
456 repo.dirstate.invalidate()
457 raise
457 raise
458 finally:
458 finally:
459 del tr, lock, wlock
459 del tr, lock, wlock
460 self.removeundo(repo)
460 self.removeundo(repo)
461
461
462 def _apply(self, repo, series, list=False, update_status=True,
462 def _apply(self, repo, series, list=False, update_status=True,
463 strict=False, patchdir=None, merge=None, all_files={}):
463 strict=False, patchdir=None, merge=None, all_files={}):
464 # TODO unify with commands.py
464 # TODO unify with commands.py
465 if not patchdir:
465 if not patchdir:
466 patchdir = self.path
466 patchdir = self.path
467 err = 0
467 err = 0
468 n = None
468 n = None
469 for patchname in series:
469 for patchname in series:
470 pushable, reason = self.pushable(patchname)
470 pushable, reason = self.pushable(patchname)
471 if not pushable:
471 if not pushable:
472 self.explain_pushable(patchname, all_patches=True)
472 self.explain_pushable(patchname, all_patches=True)
473 continue
473 continue
474 self.ui.warn("applying %s\n" % patchname)
474 self.ui.warn("applying %s\n" % patchname)
475 pf = os.path.join(patchdir, patchname)
475 pf = os.path.join(patchdir, patchname)
476
476
477 try:
477 try:
478 message, comments, user, date, patchfound = self.readheaders(patchname)
478 message, comments, user, date, patchfound = self.readheaders(patchname)
479 except:
479 except:
480 self.ui.warn("Unable to read %s\n" % patchname)
480 self.ui.warn("Unable to read %s\n" % patchname)
481 err = 1
481 err = 1
482 break
482 break
483
483
484 if not message:
484 if not message:
485 message = "imported patch %s\n" % patchname
485 message = "imported patch %s\n" % patchname
486 else:
486 else:
487 if list:
487 if list:
488 message.append("\nimported patch %s" % patchname)
488 message.append("\nimported patch %s" % patchname)
489 message = '\n'.join(message)
489 message = '\n'.join(message)
490
490
491 (patcherr, files, fuzz) = self.patch(repo, pf)
491 (patcherr, files, fuzz) = self.patch(repo, pf)
492 all_files.update(files)
492 all_files.update(files)
493 patcherr = not patcherr
493 patcherr = not patcherr
494
494
495 if merge and files:
495 if merge and files:
496 # Mark as removed/merged and update dirstate parent info
496 # Mark as removed/merged and update dirstate parent info
497 removed = []
497 removed = []
498 merged = []
498 merged = []
499 for f in files:
499 for f in files:
500 if os.path.exists(repo.wjoin(f)):
500 if os.path.exists(repo.wjoin(f)):
501 merged.append(f)
501 merged.append(f)
502 else:
502 else:
503 removed.append(f)
503 removed.append(f)
504 for f in removed:
504 for f in removed:
505 repo.dirstate.remove(f)
505 repo.dirstate.remove(f)
506 for f in merged:
506 for f in merged:
507 repo.dirstate.merge(f)
507 repo.dirstate.merge(f)
508 p1, p2 = repo.dirstate.parents()
508 p1, p2 = repo.dirstate.parents()
509 repo.dirstate.setparents(p1, merge)
509 repo.dirstate.setparents(p1, merge)
510 files = patch.updatedir(self.ui, repo, files)
510 files = patch.updatedir(self.ui, repo, files)
511 n = repo.commit(files, message, user, date, match=util.never,
511 n = repo.commit(files, message, user, date, match=util.never,
512 force=True)
512 force=True)
513
513
514 if n == None:
514 if n == None:
515 raise util.Abort(_("repo commit failed"))
515 raise util.Abort(_("repo commit failed"))
516
516
517 if update_status:
517 if update_status:
518 self.applied.append(statusentry(revlog.hex(n), patchname))
518 self.applied.append(statusentry(revlog.hex(n), patchname))
519
519
520 if patcherr:
520 if patcherr:
521 if not patchfound:
521 if not patchfound:
522 self.ui.warn("patch %s is empty\n" % patchname)
522 self.ui.warn("patch %s is empty\n" % patchname)
523 err = 0
523 err = 0
524 else:
524 else:
525 self.ui.warn("patch failed, rejects left in working dir\n")
525 self.ui.warn("patch failed, rejects left in working dir\n")
526 err = 1
526 err = 1
527 break
527 break
528
528
529 if fuzz and strict:
529 if fuzz and strict:
530 self.ui.warn("fuzz found when applying patch, stopping\n")
530 self.ui.warn("fuzz found when applying patch, stopping\n")
531 err = 1
531 err = 1
532 break
532 break
533 return (err, n)
533 return (err, n)
534
534
535 def delete(self, repo, patches, opts):
535 def delete(self, repo, patches, opts):
536 if not patches and not opts.get('rev'):
536 if not patches and not opts.get('rev'):
537 raise util.Abort(_('qdelete requires at least one revision or '
537 raise util.Abort(_('qdelete requires at least one revision or '
538 'patch name'))
538 'patch name'))
539
539
540 realpatches = []
540 realpatches = []
541 for patch in patches:
541 for patch in patches:
542 patch = self.lookup(patch, strict=True)
542 patch = self.lookup(patch, strict=True)
543 info = self.isapplied(patch)
543 info = self.isapplied(patch)
544 if info:
544 if info:
545 raise util.Abort(_("cannot delete applied patch %s") % patch)
545 raise util.Abort(_("cannot delete applied patch %s") % patch)
546 if patch not in self.series:
546 if patch not in self.series:
547 raise util.Abort(_("patch %s not in series file") % patch)
547 raise util.Abort(_("patch %s not in series file") % patch)
548 realpatches.append(patch)
548 realpatches.append(patch)
549
549
550 appliedbase = 0
550 appliedbase = 0
551 if opts.get('rev'):
551 if opts.get('rev'):
552 if not self.applied:
552 if not self.applied:
553 raise util.Abort(_('no patches applied'))
553 raise util.Abort(_('no patches applied'))
554 revs = cmdutil.revrange(repo, opts['rev'])
554 revs = cmdutil.revrange(repo, opts['rev'])
555 if len(revs) > 1 and revs[0] > revs[1]:
555 if len(revs) > 1 and revs[0] > revs[1]:
556 revs.reverse()
556 revs.reverse()
557 for rev in revs:
557 for rev in revs:
558 if appliedbase >= len(self.applied):
558 if appliedbase >= len(self.applied):
559 raise util.Abort(_("revision %d is not managed") % rev)
559 raise util.Abort(_("revision %d is not managed") % rev)
560
560
561 base = revlog.bin(self.applied[appliedbase].rev)
561 base = revlog.bin(self.applied[appliedbase].rev)
562 node = repo.changelog.node(rev)
562 node = repo.changelog.node(rev)
563 if node != base:
563 if node != base:
564 raise util.Abort(_("cannot delete revision %d above "
564 raise util.Abort(_("cannot delete revision %d above "
565 "applied patches") % rev)
565 "applied patches") % rev)
566 realpatches.append(self.applied[appliedbase].name)
566 realpatches.append(self.applied[appliedbase].name)
567 appliedbase += 1
567 appliedbase += 1
568
568
569 if not opts.get('keep'):
569 if not opts.get('keep'):
570 r = self.qrepo()
570 r = self.qrepo()
571 if r:
571 if r:
572 r.remove(realpatches, True)
572 r.remove(realpatches, True)
573 else:
573 else:
574 for p in realpatches:
574 for p in realpatches:
575 os.unlink(self.join(p))
575 os.unlink(self.join(p))
576
576
577 if appliedbase:
577 if appliedbase:
578 del self.applied[:appliedbase]
578 del self.applied[:appliedbase]
579 self.applied_dirty = 1
579 self.applied_dirty = 1
580 indices = [self.find_series(p) for p in realpatches]
580 indices = [self.find_series(p) for p in realpatches]
581 indices.sort()
581 indices.sort()
582 for i in indices[-1::-1]:
582 for i in indices[-1::-1]:
583 del self.full_series[i]
583 del self.full_series[i]
584 self.parse_series()
584 self.parse_series()
585 self.series_dirty = 1
585 self.series_dirty = 1
586
586
587 def check_toppatch(self, repo):
587 def check_toppatch(self, repo):
588 if len(self.applied) > 0:
588 if len(self.applied) > 0:
589 top = revlog.bin(self.applied[-1].rev)
589 top = revlog.bin(self.applied[-1].rev)
590 pp = repo.dirstate.parents()
590 pp = repo.dirstate.parents()
591 if top not in pp:
591 if top not in pp:
592 raise util.Abort(_("working directory revision is not qtip"))
592 raise util.Abort(_("working directory revision is not qtip"))
593 return top
593 return top
594 return None
594 return None
595 def check_localchanges(self, repo, force=False, refresh=True):
595 def check_localchanges(self, repo, force=False, refresh=True):
596 m, a, r, d = repo.status()[:4]
596 m, a, r, d = repo.status()[:4]
597 if m or a or r or d:
597 if m or a or r or d:
598 if not force:
598 if not force:
599 if refresh:
599 if refresh:
600 raise util.Abort(_("local changes found, refresh first"))
600 raise util.Abort(_("local changes found, refresh first"))
601 else:
601 else:
602 raise util.Abort(_("local changes found"))
602 raise util.Abort(_("local changes found"))
603 return m, a, r, d
603 return m, a, r, d
604
604
605 _reserved = ('series', 'status', 'guards')
605 _reserved = ('series', 'status', 'guards')
606 def check_reserved_name(self, name):
606 def check_reserved_name(self, name):
607 if (name in self._reserved or name.startswith('.hg')
607 if (name in self._reserved or name.startswith('.hg')
608 or name.startswith('.mq')):
608 or name.startswith('.mq')):
609 raise util.Abort(_('"%s" cannot be used as the name of a patch')
609 raise util.Abort(_('"%s" cannot be used as the name of a patch')
610 % name)
610 % name)
611
611
612 def new(self, repo, patch, *pats, **opts):
612 def new(self, repo, patch, *pats, **opts):
613 msg = opts.get('msg')
613 msg = opts.get('msg')
614 force = opts.get('force')
614 force = opts.get('force')
615 user = opts.get('user')
615 user = opts.get('user')
616 date = opts.get('date')
616 date = opts.get('date')
617 if date:
617 if date:
618 date = util.parsedate(date)
618 date = util.parsedate(date)
619 self.check_reserved_name(patch)
619 self.check_reserved_name(patch)
620 if os.path.exists(self.join(patch)):
620 if os.path.exists(self.join(patch)):
621 raise util.Abort(_('patch "%s" already exists') % patch)
621 raise util.Abort(_('patch "%s" already exists') % patch)
622 if opts.get('include') or opts.get('exclude') or pats:
622 if opts.get('include') or opts.get('exclude') or pats:
623 match = cmdutil.match(repo, pats, opts)
623 match = cmdutil.match(repo, pats, opts)
624 m, a, r, d = repo.status(files=match.files(), match=match)[:4]
624 m, a, r, d = repo.status(files=match.files(), match=match)[:4]
625 else:
625 else:
626 m, a, r, d = self.check_localchanges(repo, force)
626 m, a, r, d = self.check_localchanges(repo, force)
627 match = cmdutil.match(repo, m + a + r)
627 match = cmdutil.match(repo, m + a + r)
628 commitfiles = m + a + r
628 commitfiles = m + a + r
629 self.check_toppatch(repo)
629 self.check_toppatch(repo)
630 wlock = repo.wlock()
630 wlock = repo.wlock()
631 try:
631 try:
632 insert = self.full_series_end()
632 insert = self.full_series_end()
633 commitmsg = msg and msg or ("[mq]: %s" % patch)
633 commitmsg = msg and msg or ("[mq]: %s" % patch)
634 n = repo.commit(commitfiles, commitmsg, user, date, match=match, force=True)
634 n = repo.commit(commitfiles, commitmsg, user, date, match=match, force=True)
635 if n == None:
635 if n == None:
636 raise util.Abort(_("repo commit failed"))
636 raise util.Abort(_("repo commit failed"))
637 self.full_series[insert:insert] = [patch]
637 self.full_series[insert:insert] = [patch]
638 self.applied.append(statusentry(revlog.hex(n), patch))
638 self.applied.append(statusentry(revlog.hex(n), patch))
639 self.parse_series()
639 self.parse_series()
640 self.series_dirty = 1
640 self.series_dirty = 1
641 self.applied_dirty = 1
641 self.applied_dirty = 1
642 p = self.opener(patch, "w")
642 p = self.opener(patch, "w")
643 if date:
643 if date:
644 p.write("# HG changeset patch\n")
644 p.write("# HG changeset patch\n")
645 if user:
645 if user:
646 p.write("# User " + user + "\n")
646 p.write("# User " + user + "\n")
647 p.write("# Date %d %d\n" % date)
647 p.write("# Date %d %d\n" % date)
648 p.write("\n")
648 p.write("\n")
649 elif user:
649 elif user:
650 p.write("From: " + user + "\n")
650 p.write("From: " + user + "\n")
651 p.write("\n")
651 p.write("\n")
652 if msg:
652 if msg:
653 msg = msg + "\n"
653 msg = msg + "\n"
654 p.write(msg)
654 p.write(msg)
655 p.close()
655 p.close()
656 wlock = None
656 wlock = None
657 r = self.qrepo()
657 r = self.qrepo()
658 if r: r.add([patch])
658 if r: r.add([patch])
659 if commitfiles:
659 if commitfiles:
660 self.refresh(repo, short=True, git=opts.get('git'))
660 self.refresh(repo, short=True, git=opts.get('git'))
661 self.removeundo(repo)
661 self.removeundo(repo)
662 finally:
662 finally:
663 del wlock
663 del wlock
664
664
665 def strip(self, repo, rev, update=True, backup="all", force=None):
665 def strip(self, repo, rev, update=True, backup="all", force=None):
666 wlock = lock = None
666 wlock = lock = None
667 try:
667 try:
668 wlock = repo.wlock()
668 wlock = repo.wlock()
669 lock = repo.lock()
669 lock = repo.lock()
670
670
671 if update:
671 if update:
672 self.check_localchanges(repo, force=force, refresh=False)
672 self.check_localchanges(repo, force=force, refresh=False)
673 urev = self.qparents(repo, rev)
673 urev = self.qparents(repo, rev)
674 hg.clean(repo, urev)
674 hg.clean(repo, urev)
675 repo.dirstate.write()
675 repo.dirstate.write()
676
676
677 self.removeundo(repo)
677 self.removeundo(repo)
678 repair.strip(self.ui, repo, rev, backup)
678 repair.strip(self.ui, repo, rev, backup)
679 # strip may have unbundled a set of backed up revisions after
679 # strip may have unbundled a set of backed up revisions after
680 # the actual strip
680 # the actual strip
681 self.removeundo(repo)
681 self.removeundo(repo)
682 finally:
682 finally:
683 del lock, wlock
683 del lock, wlock
684
684
685 def isapplied(self, patch):
685 def isapplied(self, patch):
686 """returns (index, rev, patch)"""
686 """returns (index, rev, patch)"""
687 for i in xrange(len(self.applied)):
687 for i in xrange(len(self.applied)):
688 a = self.applied[i]
688 a = self.applied[i]
689 if a.name == patch:
689 if a.name == patch:
690 return (i, a.rev, a.name)
690 return (i, a.rev, a.name)
691 return None
691 return None
692
692
693 # if the exact patch name does not exist, we try a few
693 # if the exact patch name does not exist, we try a few
694 # variations. If strict is passed, we try only #1
694 # variations. If strict is passed, we try only #1
695 #
695 #
696 # 1) a number to indicate an offset in the series file
696 # 1) a number to indicate an offset in the series file
697 # 2) a unique substring of the patch name was given
697 # 2) a unique substring of the patch name was given
698 # 3) patchname[-+]num to indicate an offset in the series file
698 # 3) patchname[-+]num to indicate an offset in the series file
699 def lookup(self, patch, strict=False):
699 def lookup(self, patch, strict=False):
700 patch = patch and str(patch)
700 patch = patch and str(patch)
701
701
702 def partial_name(s):
702 def partial_name(s):
703 if s in self.series:
703 if s in self.series:
704 return s
704 return s
705 matches = [x for x in self.series if s in x]
705 matches = [x for x in self.series if s in x]
706 if len(matches) > 1:
706 if len(matches) > 1:
707 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
707 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
708 for m in matches:
708 for m in matches:
709 self.ui.warn(' %s\n' % m)
709 self.ui.warn(' %s\n' % m)
710 return None
710 return None
711 if matches:
711 if matches:
712 return matches[0]
712 return matches[0]
713 if len(self.series) > 0 and len(self.applied) > 0:
713 if len(self.series) > 0 and len(self.applied) > 0:
714 if s == 'qtip':
714 if s == 'qtip':
715 return self.series[self.series_end(True)-1]
715 return self.series[self.series_end(True)-1]
716 if s == 'qbase':
716 if s == 'qbase':
717 return self.series[0]
717 return self.series[0]
718 return None
718 return None
719 if patch == None:
719 if patch == None:
720 return None
720 return None
721
721
722 # we don't want to return a partial match until we make
722 # we don't want to return a partial match until we make
723 # sure the file name passed in does not exist (checked below)
723 # sure the file name passed in does not exist (checked below)
724 res = partial_name(patch)
724 res = partial_name(patch)
725 if res and res == patch:
725 if res and res == patch:
726 return res
726 return res
727
727
728 if not os.path.isfile(self.join(patch)):
728 if not os.path.isfile(self.join(patch)):
729 try:
729 try:
730 sno = int(patch)
730 sno = int(patch)
731 except(ValueError, OverflowError):
731 except(ValueError, OverflowError):
732 pass
732 pass
733 else:
733 else:
734 if sno < len(self.series):
734 if sno < len(self.series):
735 return self.series[sno]
735 return self.series[sno]
736 if not strict:
736 if not strict:
737 # return any partial match made above
737 # return any partial match made above
738 if res:
738 if res:
739 return res
739 return res
740 minus = patch.rfind('-')
740 minus = patch.rfind('-')
741 if minus >= 0:
741 if minus >= 0:
742 res = partial_name(patch[:minus])
742 res = partial_name(patch[:minus])
743 if res:
743 if res:
744 i = self.series.index(res)
744 i = self.series.index(res)
745 try:
745 try:
746 off = int(patch[minus+1:] or 1)
746 off = int(patch[minus+1:] or 1)
747 except(ValueError, OverflowError):
747 except(ValueError, OverflowError):
748 pass
748 pass
749 else:
749 else:
750 if i - off >= 0:
750 if i - off >= 0:
751 return self.series[i - off]
751 return self.series[i - off]
752 plus = patch.rfind('+')
752 plus = patch.rfind('+')
753 if plus >= 0:
753 if plus >= 0:
754 res = partial_name(patch[:plus])
754 res = partial_name(patch[:plus])
755 if res:
755 if res:
756 i = self.series.index(res)
756 i = self.series.index(res)
757 try:
757 try:
758 off = int(patch[plus+1:] or 1)
758 off = int(patch[plus+1:] or 1)
759 except(ValueError, OverflowError):
759 except(ValueError, OverflowError):
760 pass
760 pass
761 else:
761 else:
762 if i + off < len(self.series):
762 if i + off < len(self.series):
763 return self.series[i + off]
763 return self.series[i + off]
764 raise util.Abort(_("patch %s not in series") % patch)
764 raise util.Abort(_("patch %s not in series") % patch)
765
765
766 def push(self, repo, patch=None, force=False, list=False,
766 def push(self, repo, patch=None, force=False, list=False,
767 mergeq=None):
767 mergeq=None):
768 wlock = repo.wlock()
768 wlock = repo.wlock()
769 if repo.dirstate.parents()[0] != repo.changelog.tip():
769 if repo.dirstate.parents()[0] != repo.changelog.tip():
770 self.ui.status(_("(working directory not at tip)\n"))
770 self.ui.status(_("(working directory not at tip)\n"))
771
771
772 try:
772 try:
773 patch = self.lookup(patch)
773 patch = self.lookup(patch)
774 # Suppose our series file is: A B C and the current 'top'
774 # Suppose our series file is: A B C and the current 'top'
775 # patch is B. qpush C should be performed (moving forward)
775 # patch is B. qpush C should be performed (moving forward)
776 # qpush B is a NOP (no change) qpush A is an error (can't
776 # qpush B is a NOP (no change) qpush A is an error (can't
777 # go backwards with qpush)
777 # go backwards with qpush)
778 if patch:
778 if patch:
779 info = self.isapplied(patch)
779 info = self.isapplied(patch)
780 if info:
780 if info:
781 if info[0] < len(self.applied) - 1:
781 if info[0] < len(self.applied) - 1:
782 raise util.Abort(
782 raise util.Abort(
783 _("cannot push to a previous patch: %s") % patch)
783 _("cannot push to a previous patch: %s") % patch)
784 if info[0] < len(self.series) - 1:
784 if info[0] < len(self.series) - 1:
785 self.ui.warn(
785 self.ui.warn(
786 _('qpush: %s is already at the top\n') % patch)
786 _('qpush: %s is already at the top\n') % patch)
787 else:
787 else:
788 self.ui.warn(_('all patches are currently applied\n'))
788 self.ui.warn(_('all patches are currently applied\n'))
789 return
789 return
790
790
791 # Following the above example, starting at 'top' of B:
791 # Following the above example, starting at 'top' of B:
792 # qpush should be performed (pushes C), but a subsequent
792 # qpush should be performed (pushes C), but a subsequent
793 # qpush without an argument is an error (nothing to
793 # qpush without an argument is an error (nothing to
794 # apply). This allows a loop of "...while hg qpush..." to
794 # apply). This allows a loop of "...while hg qpush..." to
795 # work as it detects an error when done
795 # work as it detects an error when done
796 if self.series_end() == len(self.series):
796 if self.series_end() == len(self.series):
797 self.ui.warn(_('patch series already fully applied\n'))
797 self.ui.warn(_('patch series already fully applied\n'))
798 return 1
798 return 1
799 if not force:
799 if not force:
800 self.check_localchanges(repo)
800 self.check_localchanges(repo)
801
801
802 self.applied_dirty = 1;
802 self.applied_dirty = 1;
803 start = self.series_end()
803 start = self.series_end()
804 if start > 0:
804 if start > 0:
805 self.check_toppatch(repo)
805 self.check_toppatch(repo)
806 if not patch:
806 if not patch:
807 patch = self.series[start]
807 patch = self.series[start]
808 end = start + 1
808 end = start + 1
809 else:
809 else:
810 end = self.series.index(patch, start) + 1
810 end = self.series.index(patch, start) + 1
811 s = self.series[start:end]
811 s = self.series[start:end]
812 all_files = {}
812 all_files = {}
813 try:
813 try:
814 if mergeq:
814 if mergeq:
815 ret = self.mergepatch(repo, mergeq, s)
815 ret = self.mergepatch(repo, mergeq, s)
816 else:
816 else:
817 ret = self.apply(repo, s, list, all_files=all_files)
817 ret = self.apply(repo, s, list, all_files=all_files)
818 except:
818 except:
819 self.ui.warn(_('cleaning up working directory...'))
819 self.ui.warn(_('cleaning up working directory...'))
820 node = repo.dirstate.parents()[0]
820 node = repo.dirstate.parents()[0]
821 hg.revert(repo, node, None)
821 hg.revert(repo, node, None)
822 unknown = repo.status()[4]
822 unknown = repo.status()[4]
823 # only remove unknown files that we know we touched or
823 # only remove unknown files that we know we touched or
824 # created while patching
824 # created while patching
825 for f in unknown:
825 for f in unknown:
826 if f in all_files:
826 if f in all_files:
827 util.unlink(repo.wjoin(f))
827 util.unlink(repo.wjoin(f))
828 self.ui.warn(_('done\n'))
828 self.ui.warn(_('done\n'))
829 raise
829 raise
830 top = self.applied[-1].name
830 top = self.applied[-1].name
831 if ret[0]:
831 if ret[0]:
832 self.ui.write(
832 self.ui.write(
833 "Errors during apply, please fix and refresh %s\n" % top)
833 "Errors during apply, please fix and refresh %s\n" % top)
834 else:
834 else:
835 self.ui.write("Now at: %s\n" % top)
835 self.ui.write("Now at: %s\n" % top)
836 return ret[0]
836 return ret[0]
837 finally:
837 finally:
838 del wlock
838 del wlock
839
839
840 def pop(self, repo, patch=None, force=False, update=True, all=False):
840 def pop(self, repo, patch=None, force=False, update=True, all=False):
841 def getfile(f, rev, flags):
841 def getfile(f, rev, flags):
842 t = repo.file(f).read(rev)
842 t = repo.file(f).read(rev)
843 repo.wwrite(f, t, flags)
843 repo.wwrite(f, t, flags)
844
844
845 wlock = repo.wlock()
845 wlock = repo.wlock()
846 try:
846 try:
847 if patch:
847 if patch:
848 # index, rev, patch
848 # index, rev, patch
849 info = self.isapplied(patch)
849 info = self.isapplied(patch)
850 if not info:
850 if not info:
851 patch = self.lookup(patch)
851 patch = self.lookup(patch)
852 info = self.isapplied(patch)
852 info = self.isapplied(patch)
853 if not info:
853 if not info:
854 raise util.Abort(_("patch %s is not applied") % patch)
854 raise util.Abort(_("patch %s is not applied") % patch)
855
855
856 if len(self.applied) == 0:
856 if len(self.applied) == 0:
857 # Allow qpop -a to work repeatedly,
857 # Allow qpop -a to work repeatedly,
858 # but not qpop without an argument
858 # but not qpop without an argument
859 self.ui.warn(_("no patches applied\n"))
859 self.ui.warn(_("no patches applied\n"))
860 return not all
860 return not all
861
861
862 if not update:
862 if not update:
863 parents = repo.dirstate.parents()
863 parents = repo.dirstate.parents()
864 rr = [ revlog.bin(x.rev) for x in self.applied ]
864 rr = [ revlog.bin(x.rev) for x in self.applied ]
865 for p in parents:
865 for p in parents:
866 if p in rr:
866 if p in rr:
867 self.ui.warn("qpop: forcing dirstate update\n")
867 self.ui.warn("qpop: forcing dirstate update\n")
868 update = True
868 update = True
869
869
870 if not force and update:
870 if not force and update:
871 self.check_localchanges(repo)
871 self.check_localchanges(repo)
872
872
873 self.applied_dirty = 1;
873 self.applied_dirty = 1;
874 end = len(self.applied)
874 end = len(self.applied)
875 if not patch:
875 if not patch:
876 if all:
876 if all:
877 popi = 0
877 popi = 0
878 else:
878 else:
879 popi = len(self.applied) - 1
879 popi = len(self.applied) - 1
880 else:
880 else:
881 popi = info[0] + 1
881 popi = info[0] + 1
882 if popi >= end:
882 if popi >= end:
883 self.ui.warn("qpop: %s is already at the top\n" % patch)
883 self.ui.warn("qpop: %s is already at the top\n" % patch)
884 return
884 return
885 info = [ popi ] + [self.applied[popi].rev, self.applied[popi].name]
885 info = [ popi ] + [self.applied[popi].rev, self.applied[popi].name]
886
886
887 start = info[0]
887 start = info[0]
888 rev = revlog.bin(info[1])
888 rev = revlog.bin(info[1])
889
889
890 if update:
890 if update:
891 top = self.check_toppatch(repo)
891 top = self.check_toppatch(repo)
892
892
893 if repo.changelog.heads(rev) != [revlog.bin(self.applied[-1].rev)]:
893 if repo.changelog.heads(rev) != [revlog.bin(self.applied[-1].rev)]:
894 raise util.Abort("popping would remove a revision not "
894 raise util.Abort("popping would remove a revision not "
895 "managed by this patch queue")
895 "managed by this patch queue")
896
896
897 # we know there are no local changes, so we can make a simplified
897 # we know there are no local changes, so we can make a simplified
898 # form of hg.update.
898 # form of hg.update.
899 if update:
899 if update:
900 qp = self.qparents(repo, rev)
900 qp = self.qparents(repo, rev)
901 changes = repo.changelog.read(qp)
901 changes = repo.changelog.read(qp)
902 mmap = repo.manifest.read(changes[0])
902 mmap = repo.manifest.read(changes[0])
903 m, a, r, d, u = repo.status(qp, top)[:5]
903 m, a, r, d, u = repo.status(qp, top)[:5]
904 if d:
904 if d:
905 raise util.Abort("deletions found between repo revs")
905 raise util.Abort("deletions found between repo revs")
906 for f in m:
906 for f in m:
907 getfile(f, mmap[f], mmap.flags(f))
907 getfile(f, mmap[f], mmap.flags(f))
908 for f in r:
908 for f in r:
909 getfile(f, mmap[f], mmap.flags(f))
909 getfile(f, mmap[f], mmap.flags(f))
910 for f in m + r:
910 for f in m + r:
911 repo.dirstate.normal(f)
911 repo.dirstate.normal(f)
912 for f in a:
912 for f in a:
913 try:
913 try:
914 os.unlink(repo.wjoin(f))
914 os.unlink(repo.wjoin(f))
915 except OSError, e:
915 except OSError, e:
916 if e.errno != errno.ENOENT:
916 if e.errno != errno.ENOENT:
917 raise
917 raise
918 try: os.removedirs(os.path.dirname(repo.wjoin(f)))
918 try: os.removedirs(os.path.dirname(repo.wjoin(f)))
919 except: pass
919 except: pass
920 repo.dirstate.forget(f)
920 repo.dirstate.forget(f)
921 repo.dirstate.setparents(qp, revlog.nullid)
921 repo.dirstate.setparents(qp, revlog.nullid)
922 del self.applied[start:end]
922 del self.applied[start:end]
923 self.strip(repo, rev, update=False, backup='strip')
923 self.strip(repo, rev, update=False, backup='strip')
924 if len(self.applied):
924 if len(self.applied):
925 self.ui.write("Now at: %s\n" % self.applied[-1].name)
925 self.ui.write("Now at: %s\n" % self.applied[-1].name)
926 else:
926 else:
927 self.ui.write("Patch queue now empty\n")
927 self.ui.write("Patch queue now empty\n")
928 finally:
928 finally:
929 del wlock
929 del wlock
930
930
931 def diff(self, repo, pats, opts):
931 def diff(self, repo, pats, opts):
932 top = self.check_toppatch(repo)
932 top = self.check_toppatch(repo)
933 if not top:
933 if not top:
934 self.ui.write("No patches applied\n")
934 self.ui.write("No patches applied\n")
935 return
935 return
936 qp = self.qparents(repo, top)
936 qp = self.qparents(repo, top)
937 if opts.get('git'):
937 if opts.get('git'):
938 self.diffopts().git = True
938 self.diffopts().git = True
939 if opts.get('unified') is not None:
939 if opts.get('unified') is not None:
940 self.diffopts().context = opts['unified']
940 self.diffopts().context = opts['unified']
941 self.printdiff(repo, qp, files=pats, opts=opts)
941 self.printdiff(repo, qp, files=pats, opts=opts)
942
942
943 def refresh(self, repo, pats=None, **opts):
943 def refresh(self, repo, pats=None, **opts):
944 if len(self.applied) == 0:
944 if len(self.applied) == 0:
945 self.ui.write("No patches applied\n")
945 self.ui.write("No patches applied\n")
946 return 1
946 return 1
947 newdate = opts.get('date')
947 newdate = opts.get('date')
948 if newdate:
948 if newdate:
949 newdate = '%d %d' % util.parsedate(newdate)
949 newdate = '%d %d' % util.parsedate(newdate)
950 wlock = repo.wlock()
950 wlock = repo.wlock()
951 try:
951 try:
952 self.check_toppatch(repo)
952 self.check_toppatch(repo)
953 (top, patchfn) = (self.applied[-1].rev, self.applied[-1].name)
953 (top, patchfn) = (self.applied[-1].rev, self.applied[-1].name)
954 top = revlog.bin(top)
954 top = revlog.bin(top)
955 if repo.changelog.heads(top) != [top]:
955 if repo.changelog.heads(top) != [top]:
956 raise util.Abort("cannot refresh a revision with children")
956 raise util.Abort("cannot refresh a revision with children")
957 cparents = repo.changelog.parents(top)
957 cparents = repo.changelog.parents(top)
958 patchparent = self.qparents(repo, top)
958 patchparent = self.qparents(repo, top)
959 message, comments, user, date, patchfound = self.readheaders(patchfn)
959 message, comments, user, date, patchfound = self.readheaders(patchfn)
960
960
961 patchf = self.opener(patchfn, 'r+')
961 patchf = self.opener(patchfn, 'r+')
962
962
963 # if the patch was a git patch, refresh it as a git patch
963 # if the patch was a git patch, refresh it as a git patch
964 for line in patchf:
964 for line in patchf:
965 if line.startswith('diff --git'):
965 if line.startswith('diff --git'):
966 self.diffopts().git = True
966 self.diffopts().git = True
967 break
967 break
968
968
969 msg = opts.get('msg', '').rstrip()
969 msg = opts.get('msg', '').rstrip()
970 if msg and comments:
970 if msg and comments:
971 # Remove existing message, keeping the rest of the comments
971 # Remove existing message, keeping the rest of the comments
972 # fields.
972 # fields.
973 # If comments contains 'subject: ', message will prepend
973 # If comments contains 'subject: ', message will prepend
974 # the field and a blank line.
974 # the field and a blank line.
975 if message:
975 if message:
976 subj = 'subject: ' + message[0].lower()
976 subj = 'subject: ' + message[0].lower()
977 for i in xrange(len(comments)):
977 for i in xrange(len(comments)):
978 if subj == comments[i].lower():
978 if subj == comments[i].lower():
979 del comments[i]
979 del comments[i]
980 message = message[2:]
980 message = message[2:]
981 break
981 break
982 ci = 0
982 ci = 0
983 for mi in xrange(len(message)):
983 for mi in xrange(len(message)):
984 while message[mi] != comments[ci]:
984 while message[mi] != comments[ci]:
985 ci += 1
985 ci += 1
986 del comments[ci]
986 del comments[ci]
987
987
988 def setheaderfield(comments, prefixes, new):
988 def setheaderfield(comments, prefixes, new):
989 # Update all references to a field in the patch header.
989 # Update all references to a field in the patch header.
990 # If none found, add it email style.
990 # If none found, add it email style.
991 res = False
991 res = False
992 for prefix in prefixes:
992 for prefix in prefixes:
993 for i in xrange(len(comments)):
993 for i in xrange(len(comments)):
994 if comments[i].startswith(prefix):
994 if comments[i].startswith(prefix):
995 comments[i] = prefix + new
995 comments[i] = prefix + new
996 res = True
996 res = True
997 break
997 break
998 return res
998 return res
999
999
1000 newuser = opts.get('user')
1000 newuser = opts.get('user')
1001 if newuser:
1001 if newuser:
1002 if not setheaderfield(comments, ['From: ', '# User '], newuser):
1002 if not setheaderfield(comments, ['From: ', '# User '], newuser):
1003 try:
1003 try:
1004 patchheaderat = comments.index('# HG changeset patch')
1004 patchheaderat = comments.index('# HG changeset patch')
1005 comments.insert(patchheaderat + 1,'# User ' + newuser)
1005 comments.insert(patchheaderat + 1,'# User ' + newuser)
1006 except ValueError:
1006 except ValueError:
1007 comments = ['From: ' + newuser, ''] + comments
1007 comments = ['From: ' + newuser, ''] + comments
1008 user = newuser
1008 user = newuser
1009
1009
1010 if newdate:
1010 if newdate:
1011 if setheaderfield(comments, ['# Date '], newdate):
1011 if setheaderfield(comments, ['# Date '], newdate):
1012 date = newdate
1012 date = newdate
1013
1013
1014 if msg:
1014 if msg:
1015 comments.append(msg)
1015 comments.append(msg)
1016
1016
1017 patchf.seek(0)
1017 patchf.seek(0)
1018 patchf.truncate()
1018 patchf.truncate()
1019
1019
1020 if comments:
1020 if comments:
1021 comments = "\n".join(comments) + '\n\n'
1021 comments = "\n".join(comments) + '\n\n'
1022 patchf.write(comments)
1022 patchf.write(comments)
1023
1023
1024 if opts.get('git'):
1024 if opts.get('git'):
1025 self.diffopts().git = True
1025 self.diffopts().git = True
1026 matchfn = cmdutil.match(repo, pats, opts)
1026 matchfn = cmdutil.match(repo, pats, opts)
1027 tip = repo.changelog.tip()
1027 tip = repo.changelog.tip()
1028 if top == tip:
1028 if top == tip:
1029 # if the top of our patch queue is also the tip, there is an
1029 # if the top of our patch queue is also the tip, there is an
1030 # optimization here. We update the dirstate in place and strip
1030 # optimization here. We update the dirstate in place and strip
1031 # off the tip commit. Then just commit the current directory
1031 # off the tip commit. Then just commit the current directory
1032 # tree. We can also send repo.commit the list of files
1032 # tree. We can also send repo.commit the list of files
1033 # changed to speed up the diff
1033 # changed to speed up the diff
1034 #
1034 #
1035 # in short mode, we only diff the files included in the
1035 # in short mode, we only diff the files included in the
1036 # patch already
1036 # patch already
1037 #
1037 #
1038 # this should really read:
1038 # this should really read:
1039 # mm, dd, aa, aa2, uu = repo.status(tip, patchparent)[:5]
1039 # mm, dd, aa, aa2, uu = repo.status(tip, patchparent)[:5]
1040 # but we do it backwards to take advantage of manifest/chlog
1040 # but we do it backwards to take advantage of manifest/chlog
1041 # caching against the next repo.status call
1041 # caching against the next repo.status call
1042 #
1042 #
1043 mm, aa, dd, aa2, uu = repo.status(patchparent, tip)[:5]
1043 mm, aa, dd, aa2, uu = repo.status(patchparent, tip)[:5]
1044 changes = repo.changelog.read(tip)
1044 changes = repo.changelog.read(tip)
1045 man = repo.manifest.read(changes[0])
1045 man = repo.manifest.read(changes[0])
1046 aaa = aa[:]
1046 aaa = aa[:]
1047 if opts.get('short'):
1047 if opts.get('short'):
1048 match = cmdutil.matchfiles(repo, mm + aa + dd)
1048 match = cmdutil.matchfiles(repo, mm + aa + dd)
1049 else:
1049 else:
1050 match = cmdutil.matchall(repo)
1050 match = cmdutil.matchall(repo)
1051 m, a, r, d, u = repo.status(files=match.files(), match=match)[:5]
1051 m, a, r, d, u = repo.status(files=match.files(), match=match)[:5]
1052
1052
1053 # we might end up with files that were added between
1053 # we might end up with files that were added between
1054 # tip and the dirstate parent, but then changed in the
1054 # tip and the dirstate parent, but then changed in the
1055 # local dirstate. in this case, we want them to only
1055 # local dirstate. in this case, we want them to only
1056 # show up in the added section
1056 # show up in the added section
1057 for x in m:
1057 for x in m:
1058 if x not in aa:
1058 if x not in aa:
1059 mm.append(x)
1059 mm.append(x)
1060 # we might end up with files added by the local dirstate that
1060 # we might end up with files added by the local dirstate that
1061 # were deleted by the patch. In this case, they should only
1061 # were deleted by the patch. In this case, they should only
1062 # show up in the changed section.
1062 # show up in the changed section.
1063 for x in a:
1063 for x in a:
1064 if x in dd:
1064 if x in dd:
1065 del dd[dd.index(x)]
1065 del dd[dd.index(x)]
1066 mm.append(x)
1066 mm.append(x)
1067 else:
1067 else:
1068 aa.append(x)
1068 aa.append(x)
1069 # make sure any files deleted in the local dirstate
1069 # make sure any files deleted in the local dirstate
1070 # are not in the add or change column of the patch
1070 # are not in the add or change column of the patch
1071 forget = []
1071 forget = []
1072 for x in d + r:
1072 for x in d + r:
1073 if x in aa:
1073 if x in aa:
1074 del aa[aa.index(x)]
1074 del aa[aa.index(x)]
1075 forget.append(x)
1075 forget.append(x)
1076 continue
1076 continue
1077 elif x in mm:
1077 elif x in mm:
1078 del mm[mm.index(x)]
1078 del mm[mm.index(x)]
1079 dd.append(x)
1079 dd.append(x)
1080
1080
1081 m = util.unique(mm)
1081 m = util.unique(mm)
1082 r = util.unique(dd)
1082 r = util.unique(dd)
1083 a = util.unique(aa)
1083 a = util.unique(aa)
1084 c = [filter(matchfn, l) for l in (m, a, r, [], u)]
1084 c = [filter(matchfn, l) for l in (m, a, r, [], u)]
1085 filelist = util.unique(c[0] + c[1] + c[2])
1085 match = cmdutil.matchfiles(repo, util.unique(c[0] + c[1] + c[2]))
1086 patch.diff(repo, patchparent, files=filelist, match=matchfn,
1086 patch.diff(repo, patchparent, files=match.files(), match=match,
1087 fp=patchf, changes=c, opts=self.diffopts())
1087 fp=patchf, changes=c, opts=self.diffopts())
1088 patchf.close()
1088 patchf.close()
1089
1089
1090 repo.dirstate.setparents(*cparents)
1090 repo.dirstate.setparents(*cparents)
1091 copies = {}
1091 copies = {}
1092 for dst in a:
1092 for dst in a:
1093 src = repo.dirstate.copied(dst)
1093 src = repo.dirstate.copied(dst)
1094 if src is not None:
1094 if src is not None:
1095 copies.setdefault(src, []).append(dst)
1095 copies.setdefault(src, []).append(dst)
1096 repo.dirstate.add(dst)
1096 repo.dirstate.add(dst)
1097 # remember the copies between patchparent and tip
1097 # remember the copies between patchparent and tip
1098 # this may be slow, so don't do it if we're not tracking copies
1098 # this may be slow, so don't do it if we're not tracking copies
1099 if self.diffopts().git:
1099 if self.diffopts().git:
1100 for dst in aaa:
1100 for dst in aaa:
1101 f = repo.file(dst)
1101 f = repo.file(dst)
1102 src = f.renamed(man[dst])
1102 src = f.renamed(man[dst])
1103 if src:
1103 if src:
1104 copies[src[0]] = copies.get(dst, [])
1104 copies[src[0]] = copies.get(dst, [])
1105 if dst in a:
1105 if dst in a:
1106 copies[src[0]].append(dst)
1106 copies[src[0]].append(dst)
1107 # we can't copy a file created by the patch itself
1107 # we can't copy a file created by the patch itself
1108 if dst in copies:
1108 if dst in copies:
1109 del copies[dst]
1109 del copies[dst]
1110 for src, dsts in copies.iteritems():
1110 for src, dsts in copies.iteritems():
1111 for dst in dsts:
1111 for dst in dsts:
1112 repo.dirstate.copy(src, dst)
1112 repo.dirstate.copy(src, dst)
1113 for f in r:
1113 for f in r:
1114 repo.dirstate.remove(f)
1114 repo.dirstate.remove(f)
1115 # if the patch excludes a modified file, mark that
1115 # if the patch excludes a modified file, mark that
1116 # file with mtime=0 so status can see it.
1116 # file with mtime=0 so status can see it.
1117 mm = []
1117 mm = []
1118 for i in xrange(len(m)-1, -1, -1):
1118 for i in xrange(len(m)-1, -1, -1):
1119 if not matchfn(m[i]):
1119 if not matchfn(m[i]):
1120 mm.append(m[i])
1120 mm.append(m[i])
1121 del m[i]
1121 del m[i]
1122 for f in m:
1122 for f in m:
1123 repo.dirstate.normal(f)
1123 repo.dirstate.normal(f)
1124 for f in mm:
1124 for f in mm:
1125 repo.dirstate.normallookup(f)
1125 repo.dirstate.normallookup(f)
1126 for f in forget:
1126 for f in forget:
1127 repo.dirstate.forget(f)
1127 repo.dirstate.forget(f)
1128
1128
1129 if not msg:
1129 if not msg:
1130 if not message:
1130 if not message:
1131 message = "[mq]: %s\n" % patchfn
1131 message = "[mq]: %s\n" % patchfn
1132 else:
1132 else:
1133 message = "\n".join(message)
1133 message = "\n".join(message)
1134 else:
1134 else:
1135 message = msg
1135 message = msg
1136
1136
1137 if not user:
1137 if not user:
1138 user = changes[1]
1138 user = changes[1]
1139
1139
1140 self.applied.pop()
1140 self.applied.pop()
1141 self.applied_dirty = 1
1141 self.applied_dirty = 1
1142 self.strip(repo, top, update=False,
1142 self.strip(repo, top, update=False,
1143 backup='strip')
1143 backup='strip')
1144 n = repo.commit(filelist, message, user, date, match=matchfn,
1144 n = repo.commit(match.files(), message, user, date, match=match,
1145 force=1)
1145 force=1)
1146 self.applied.append(statusentry(revlog.hex(n), patchfn))
1146 self.applied.append(statusentry(revlog.hex(n), patchfn))
1147 self.removeundo(repo)
1147 self.removeundo(repo)
1148 else:
1148 else:
1149 self.printdiff(repo, patchparent, fp=patchf)
1149 self.printdiff(repo, patchparent, fp=patchf)
1150 patchf.close()
1150 patchf.close()
1151 added = repo.status()[1]
1151 added = repo.status()[1]
1152 for a in added:
1152 for a in added:
1153 f = repo.wjoin(a)
1153 f = repo.wjoin(a)
1154 try:
1154 try:
1155 os.unlink(f)
1155 os.unlink(f)
1156 except OSError, e:
1156 except OSError, e:
1157 if e.errno != errno.ENOENT:
1157 if e.errno != errno.ENOENT:
1158 raise
1158 raise
1159 try: os.removedirs(os.path.dirname(f))
1159 try: os.removedirs(os.path.dirname(f))
1160 except: pass
1160 except: pass
1161 # forget the file copies in the dirstate
1161 # forget the file copies in the dirstate
1162 # push should readd the files later on
1162 # push should readd the files later on
1163 repo.dirstate.forget(a)
1163 repo.dirstate.forget(a)
1164 self.pop(repo, force=True)
1164 self.pop(repo, force=True)
1165 self.push(repo, force=True)
1165 self.push(repo, force=True)
1166 finally:
1166 finally:
1167 del wlock
1167 del wlock
1168
1168
1169 def init(self, repo, create=False):
1169 def init(self, repo, create=False):
1170 if not create and os.path.isdir(self.path):
1170 if not create and os.path.isdir(self.path):
1171 raise util.Abort(_("patch queue directory already exists"))
1171 raise util.Abort(_("patch queue directory already exists"))
1172 try:
1172 try:
1173 os.mkdir(self.path)
1173 os.mkdir(self.path)
1174 except OSError, inst:
1174 except OSError, inst:
1175 if inst.errno != errno.EEXIST or not create:
1175 if inst.errno != errno.EEXIST or not create:
1176 raise
1176 raise
1177 if create:
1177 if create:
1178 return self.qrepo(create=True)
1178 return self.qrepo(create=True)
1179
1179
1180 def unapplied(self, repo, patch=None):
1180 def unapplied(self, repo, patch=None):
1181 if patch and patch not in self.series:
1181 if patch and patch not in self.series:
1182 raise util.Abort(_("patch %s is not in series file") % patch)
1182 raise util.Abort(_("patch %s is not in series file") % patch)
1183 if not patch:
1183 if not patch:
1184 start = self.series_end()
1184 start = self.series_end()
1185 else:
1185 else:
1186 start = self.series.index(patch) + 1
1186 start = self.series.index(patch) + 1
1187 unapplied = []
1187 unapplied = []
1188 for i in xrange(start, len(self.series)):
1188 for i in xrange(start, len(self.series)):
1189 pushable, reason = self.pushable(i)
1189 pushable, reason = self.pushable(i)
1190 if pushable:
1190 if pushable:
1191 unapplied.append((i, self.series[i]))
1191 unapplied.append((i, self.series[i]))
1192 self.explain_pushable(i)
1192 self.explain_pushable(i)
1193 return unapplied
1193 return unapplied
1194
1194
1195 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1195 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1196 summary=False):
1196 summary=False):
1197 def displayname(patchname):
1197 def displayname(patchname):
1198 if summary:
1198 if summary:
1199 msg = self.readheaders(patchname)[0]
1199 msg = self.readheaders(patchname)[0]
1200 msg = msg and ': ' + msg[0] or ': '
1200 msg = msg and ': ' + msg[0] or ': '
1201 else:
1201 else:
1202 msg = ''
1202 msg = ''
1203 return '%s%s' % (patchname, msg)
1203 return '%s%s' % (patchname, msg)
1204
1204
1205 applied = dict.fromkeys([p.name for p in self.applied])
1205 applied = dict.fromkeys([p.name for p in self.applied])
1206 if length is None:
1206 if length is None:
1207 length = len(self.series) - start
1207 length = len(self.series) - start
1208 if not missing:
1208 if not missing:
1209 for i in xrange(start, start+length):
1209 for i in xrange(start, start+length):
1210 patch = self.series[i]
1210 patch = self.series[i]
1211 if patch in applied:
1211 if patch in applied:
1212 stat = 'A'
1212 stat = 'A'
1213 elif self.pushable(i)[0]:
1213 elif self.pushable(i)[0]:
1214 stat = 'U'
1214 stat = 'U'
1215 else:
1215 else:
1216 stat = 'G'
1216 stat = 'G'
1217 pfx = ''
1217 pfx = ''
1218 if self.ui.verbose:
1218 if self.ui.verbose:
1219 pfx = '%d %s ' % (i, stat)
1219 pfx = '%d %s ' % (i, stat)
1220 elif status and status != stat:
1220 elif status and status != stat:
1221 continue
1221 continue
1222 self.ui.write('%s%s\n' % (pfx, displayname(patch)))
1222 self.ui.write('%s%s\n' % (pfx, displayname(patch)))
1223 else:
1223 else:
1224 msng_list = []
1224 msng_list = []
1225 for root, dirs, files in os.walk(self.path):
1225 for root, dirs, files in os.walk(self.path):
1226 d = root[len(self.path) + 1:]
1226 d = root[len(self.path) + 1:]
1227 for f in files:
1227 for f in files:
1228 fl = os.path.join(d, f)
1228 fl = os.path.join(d, f)
1229 if (fl not in self.series and
1229 if (fl not in self.series and
1230 fl not in (self.status_path, self.series_path,
1230 fl not in (self.status_path, self.series_path,
1231 self.guards_path)
1231 self.guards_path)
1232 and not fl.startswith('.')):
1232 and not fl.startswith('.')):
1233 msng_list.append(fl)
1233 msng_list.append(fl)
1234 msng_list.sort()
1234 msng_list.sort()
1235 for x in msng_list:
1235 for x in msng_list:
1236 pfx = self.ui.verbose and ('D ') or ''
1236 pfx = self.ui.verbose and ('D ') or ''
1237 self.ui.write("%s%s\n" % (pfx, displayname(x)))
1237 self.ui.write("%s%s\n" % (pfx, displayname(x)))
1238
1238
1239 def issaveline(self, l):
1239 def issaveline(self, l):
1240 if l.name == '.hg.patches.save.line':
1240 if l.name == '.hg.patches.save.line':
1241 return True
1241 return True
1242
1242
1243 def qrepo(self, create=False):
1243 def qrepo(self, create=False):
1244 if create or os.path.isdir(self.join(".hg")):
1244 if create or os.path.isdir(self.join(".hg")):
1245 return hg.repository(self.ui, path=self.path, create=create)
1245 return hg.repository(self.ui, path=self.path, create=create)
1246
1246
1247 def restore(self, repo, rev, delete=None, qupdate=None):
1247 def restore(self, repo, rev, delete=None, qupdate=None):
1248 c = repo.changelog.read(rev)
1248 c = repo.changelog.read(rev)
1249 desc = c[4].strip()
1249 desc = c[4].strip()
1250 lines = desc.splitlines()
1250 lines = desc.splitlines()
1251 i = 0
1251 i = 0
1252 datastart = None
1252 datastart = None
1253 series = []
1253 series = []
1254 applied = []
1254 applied = []
1255 qpp = None
1255 qpp = None
1256 for i in xrange(0, len(lines)):
1256 for i in xrange(0, len(lines)):
1257 if lines[i] == 'Patch Data:':
1257 if lines[i] == 'Patch Data:':
1258 datastart = i + 1
1258 datastart = i + 1
1259 elif lines[i].startswith('Dirstate:'):
1259 elif lines[i].startswith('Dirstate:'):
1260 l = lines[i].rstrip()
1260 l = lines[i].rstrip()
1261 l = l[10:].split(' ')
1261 l = l[10:].split(' ')
1262 qpp = [ bin(x) for x in l ]
1262 qpp = [ bin(x) for x in l ]
1263 elif datastart != None:
1263 elif datastart != None:
1264 l = lines[i].rstrip()
1264 l = lines[i].rstrip()
1265 se = statusentry(l)
1265 se = statusentry(l)
1266 file_ = se.name
1266 file_ = se.name
1267 if se.rev:
1267 if se.rev:
1268 applied.append(se)
1268 applied.append(se)
1269 else:
1269 else:
1270 series.append(file_)
1270 series.append(file_)
1271 if datastart == None:
1271 if datastart == None:
1272 self.ui.warn("No saved patch data found\n")
1272 self.ui.warn("No saved patch data found\n")
1273 return 1
1273 return 1
1274 self.ui.warn("restoring status: %s\n" % lines[0])
1274 self.ui.warn("restoring status: %s\n" % lines[0])
1275 self.full_series = series
1275 self.full_series = series
1276 self.applied = applied
1276 self.applied = applied
1277 self.parse_series()
1277 self.parse_series()
1278 self.series_dirty = 1
1278 self.series_dirty = 1
1279 self.applied_dirty = 1
1279 self.applied_dirty = 1
1280 heads = repo.changelog.heads()
1280 heads = repo.changelog.heads()
1281 if delete:
1281 if delete:
1282 if rev not in heads:
1282 if rev not in heads:
1283 self.ui.warn("save entry has children, leaving it alone\n")
1283 self.ui.warn("save entry has children, leaving it alone\n")
1284 else:
1284 else:
1285 self.ui.warn("removing save entry %s\n" % short(rev))
1285 self.ui.warn("removing save entry %s\n" % short(rev))
1286 pp = repo.dirstate.parents()
1286 pp = repo.dirstate.parents()
1287 if rev in pp:
1287 if rev in pp:
1288 update = True
1288 update = True
1289 else:
1289 else:
1290 update = False
1290 update = False
1291 self.strip(repo, rev, update=update, backup='strip')
1291 self.strip(repo, rev, update=update, backup='strip')
1292 if qpp:
1292 if qpp:
1293 self.ui.warn("saved queue repository parents: %s %s\n" %
1293 self.ui.warn("saved queue repository parents: %s %s\n" %
1294 (short(qpp[0]), short(qpp[1])))
1294 (short(qpp[0]), short(qpp[1])))
1295 if qupdate:
1295 if qupdate:
1296 self.ui.status(_("queue directory updating\n"))
1296 self.ui.status(_("queue directory updating\n"))
1297 r = self.qrepo()
1297 r = self.qrepo()
1298 if not r:
1298 if not r:
1299 self.ui.warn("Unable to load queue repository\n")
1299 self.ui.warn("Unable to load queue repository\n")
1300 return 1
1300 return 1
1301 hg.clean(r, qpp[0])
1301 hg.clean(r, qpp[0])
1302
1302
1303 def save(self, repo, msg=None):
1303 def save(self, repo, msg=None):
1304 if len(self.applied) == 0:
1304 if len(self.applied) == 0:
1305 self.ui.warn("save: no patches applied, exiting\n")
1305 self.ui.warn("save: no patches applied, exiting\n")
1306 return 1
1306 return 1
1307 if self.issaveline(self.applied[-1]):
1307 if self.issaveline(self.applied[-1]):
1308 self.ui.warn("status is already saved\n")
1308 self.ui.warn("status is already saved\n")
1309 return 1
1309 return 1
1310
1310
1311 ar = [ ':' + x for x in self.full_series ]
1311 ar = [ ':' + x for x in self.full_series ]
1312 if not msg:
1312 if not msg:
1313 msg = "hg patches saved state"
1313 msg = "hg patches saved state"
1314 else:
1314 else:
1315 msg = "hg patches: " + msg.rstrip('\r\n')
1315 msg = "hg patches: " + msg.rstrip('\r\n')
1316 r = self.qrepo()
1316 r = self.qrepo()
1317 if r:
1317 if r:
1318 pp = r.dirstate.parents()
1318 pp = r.dirstate.parents()
1319 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1319 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1320 msg += "\n\nPatch Data:\n"
1320 msg += "\n\nPatch Data:\n"
1321 text = msg + "\n".join([str(x) for x in self.applied]) + '\n' + (ar and
1321 text = msg + "\n".join([str(x) for x in self.applied]) + '\n' + (ar and
1322 "\n".join(ar) + '\n' or "")
1322 "\n".join(ar) + '\n' or "")
1323 n = repo.commit(None, text, user=None, force=1)
1323 n = repo.commit(None, text, user=None, force=1)
1324 if not n:
1324 if not n:
1325 self.ui.warn("repo commit failed\n")
1325 self.ui.warn("repo commit failed\n")
1326 return 1
1326 return 1
1327 self.applied.append(statusentry(revlog.hex(n),'.hg.patches.save.line'))
1327 self.applied.append(statusentry(revlog.hex(n),'.hg.patches.save.line'))
1328 self.applied_dirty = 1
1328 self.applied_dirty = 1
1329 self.removeundo(repo)
1329 self.removeundo(repo)
1330
1330
1331 def full_series_end(self):
1331 def full_series_end(self):
1332 if len(self.applied) > 0:
1332 if len(self.applied) > 0:
1333 p = self.applied[-1].name
1333 p = self.applied[-1].name
1334 end = self.find_series(p)
1334 end = self.find_series(p)
1335 if end == None:
1335 if end == None:
1336 return len(self.full_series)
1336 return len(self.full_series)
1337 return end + 1
1337 return end + 1
1338 return 0
1338 return 0
1339
1339
1340 def series_end(self, all_patches=False):
1340 def series_end(self, all_patches=False):
1341 """If all_patches is False, return the index of the next pushable patch
1341 """If all_patches is False, return the index of the next pushable patch
1342 in the series, or the series length. If all_patches is True, return the
1342 in the series, or the series length. If all_patches is True, return the
1343 index of the first patch past the last applied one.
1343 index of the first patch past the last applied one.
1344 """
1344 """
1345 end = 0
1345 end = 0
1346 def next(start):
1346 def next(start):
1347 if all_patches:
1347 if all_patches:
1348 return start
1348 return start
1349 i = start
1349 i = start
1350 while i < len(self.series):
1350 while i < len(self.series):
1351 p, reason = self.pushable(i)
1351 p, reason = self.pushable(i)
1352 if p:
1352 if p:
1353 break
1353 break
1354 self.explain_pushable(i)
1354 self.explain_pushable(i)
1355 i += 1
1355 i += 1
1356 return i
1356 return i
1357 if len(self.applied) > 0:
1357 if len(self.applied) > 0:
1358 p = self.applied[-1].name
1358 p = self.applied[-1].name
1359 try:
1359 try:
1360 end = self.series.index(p)
1360 end = self.series.index(p)
1361 except ValueError:
1361 except ValueError:
1362 return 0
1362 return 0
1363 return next(end + 1)
1363 return next(end + 1)
1364 return next(end)
1364 return next(end)
1365
1365
1366 def appliedname(self, index):
1366 def appliedname(self, index):
1367 pname = self.applied[index].name
1367 pname = self.applied[index].name
1368 if not self.ui.verbose:
1368 if not self.ui.verbose:
1369 p = pname
1369 p = pname
1370 else:
1370 else:
1371 p = str(self.series.index(pname)) + " " + pname
1371 p = str(self.series.index(pname)) + " " + pname
1372 return p
1372 return p
1373
1373
1374 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1374 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1375 force=None, git=False):
1375 force=None, git=False):
1376 def checkseries(patchname):
1376 def checkseries(patchname):
1377 if patchname in self.series:
1377 if patchname in self.series:
1378 raise util.Abort(_('patch %s is already in the series file')
1378 raise util.Abort(_('patch %s is already in the series file')
1379 % patchname)
1379 % patchname)
1380 def checkfile(patchname):
1380 def checkfile(patchname):
1381 if not force and os.path.exists(self.join(patchname)):
1381 if not force and os.path.exists(self.join(patchname)):
1382 raise util.Abort(_('patch "%s" already exists')
1382 raise util.Abort(_('patch "%s" already exists')
1383 % patchname)
1383 % patchname)
1384
1384
1385 if rev:
1385 if rev:
1386 if files:
1386 if files:
1387 raise util.Abort(_('option "-r" not valid when importing '
1387 raise util.Abort(_('option "-r" not valid when importing '
1388 'files'))
1388 'files'))
1389 rev = cmdutil.revrange(repo, rev)
1389 rev = cmdutil.revrange(repo, rev)
1390 rev.sort(lambda x, y: cmp(y, x))
1390 rev.sort(lambda x, y: cmp(y, x))
1391 if (len(files) > 1 or len(rev) > 1) and patchname:
1391 if (len(files) > 1 or len(rev) > 1) and patchname:
1392 raise util.Abort(_('option "-n" not valid when importing multiple '
1392 raise util.Abort(_('option "-n" not valid when importing multiple '
1393 'patches'))
1393 'patches'))
1394 i = 0
1394 i = 0
1395 added = []
1395 added = []
1396 if rev:
1396 if rev:
1397 # If mq patches are applied, we can only import revisions
1397 # If mq patches are applied, we can only import revisions
1398 # that form a linear path to qbase.
1398 # that form a linear path to qbase.
1399 # Otherwise, they should form a linear path to a head.
1399 # Otherwise, they should form a linear path to a head.
1400 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1400 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1401 if len(heads) > 1:
1401 if len(heads) > 1:
1402 raise util.Abort(_('revision %d is the root of more than one '
1402 raise util.Abort(_('revision %d is the root of more than one '
1403 'branch') % rev[-1])
1403 'branch') % rev[-1])
1404 if self.applied:
1404 if self.applied:
1405 base = revlog.hex(repo.changelog.node(rev[0]))
1405 base = revlog.hex(repo.changelog.node(rev[0]))
1406 if base in [n.rev for n in self.applied]:
1406 if base in [n.rev for n in self.applied]:
1407 raise util.Abort(_('revision %d is already managed')
1407 raise util.Abort(_('revision %d is already managed')
1408 % rev[0])
1408 % rev[0])
1409 if heads != [revlog.bin(self.applied[-1].rev)]:
1409 if heads != [revlog.bin(self.applied[-1].rev)]:
1410 raise util.Abort(_('revision %d is not the parent of '
1410 raise util.Abort(_('revision %d is not the parent of '
1411 'the queue') % rev[0])
1411 'the queue') % rev[0])
1412 base = repo.changelog.rev(revlog.bin(self.applied[0].rev))
1412 base = repo.changelog.rev(revlog.bin(self.applied[0].rev))
1413 lastparent = repo.changelog.parentrevs(base)[0]
1413 lastparent = repo.changelog.parentrevs(base)[0]
1414 else:
1414 else:
1415 if heads != [repo.changelog.node(rev[0])]:
1415 if heads != [repo.changelog.node(rev[0])]:
1416 raise util.Abort(_('revision %d has unmanaged children')
1416 raise util.Abort(_('revision %d has unmanaged children')
1417 % rev[0])
1417 % rev[0])
1418 lastparent = None
1418 lastparent = None
1419
1419
1420 if git:
1420 if git:
1421 self.diffopts().git = True
1421 self.diffopts().git = True
1422
1422
1423 for r in rev:
1423 for r in rev:
1424 p1, p2 = repo.changelog.parentrevs(r)
1424 p1, p2 = repo.changelog.parentrevs(r)
1425 n = repo.changelog.node(r)
1425 n = repo.changelog.node(r)
1426 if p2 != revlog.nullrev:
1426 if p2 != revlog.nullrev:
1427 raise util.Abort(_('cannot import merge revision %d') % r)
1427 raise util.Abort(_('cannot import merge revision %d') % r)
1428 if lastparent and lastparent != r:
1428 if lastparent and lastparent != r:
1429 raise util.Abort(_('revision %d is not the parent of %d')
1429 raise util.Abort(_('revision %d is not the parent of %d')
1430 % (r, lastparent))
1430 % (r, lastparent))
1431 lastparent = p1
1431 lastparent = p1
1432
1432
1433 if not patchname:
1433 if not patchname:
1434 patchname = normname('%d.diff' % r)
1434 patchname = normname('%d.diff' % r)
1435 self.check_reserved_name(patchname)
1435 self.check_reserved_name(patchname)
1436 checkseries(patchname)
1436 checkseries(patchname)
1437 checkfile(patchname)
1437 checkfile(patchname)
1438 self.full_series.insert(0, patchname)
1438 self.full_series.insert(0, patchname)
1439
1439
1440 patchf = self.opener(patchname, "w")
1440 patchf = self.opener(patchname, "w")
1441 patch.export(repo, [n], fp=patchf, opts=self.diffopts())
1441 patch.export(repo, [n], fp=patchf, opts=self.diffopts())
1442 patchf.close()
1442 patchf.close()
1443
1443
1444 se = statusentry(revlog.hex(n), patchname)
1444 se = statusentry(revlog.hex(n), patchname)
1445 self.applied.insert(0, se)
1445 self.applied.insert(0, se)
1446
1446
1447 added.append(patchname)
1447 added.append(patchname)
1448 patchname = None
1448 patchname = None
1449 self.parse_series()
1449 self.parse_series()
1450 self.applied_dirty = 1
1450 self.applied_dirty = 1
1451
1451
1452 for filename in files:
1452 for filename in files:
1453 if existing:
1453 if existing:
1454 if filename == '-':
1454 if filename == '-':
1455 raise util.Abort(_('-e is incompatible with import from -'))
1455 raise util.Abort(_('-e is incompatible with import from -'))
1456 if not patchname:
1456 if not patchname:
1457 patchname = normname(filename)
1457 patchname = normname(filename)
1458 self.check_reserved_name(patchname)
1458 self.check_reserved_name(patchname)
1459 if not os.path.isfile(self.join(patchname)):
1459 if not os.path.isfile(self.join(patchname)):
1460 raise util.Abort(_("patch %s does not exist") % patchname)
1460 raise util.Abort(_("patch %s does not exist") % patchname)
1461 else:
1461 else:
1462 try:
1462 try:
1463 if filename == '-':
1463 if filename == '-':
1464 if not patchname:
1464 if not patchname:
1465 raise util.Abort(_('need --name to import a patch from -'))
1465 raise util.Abort(_('need --name to import a patch from -'))
1466 text = sys.stdin.read()
1466 text = sys.stdin.read()
1467 else:
1467 else:
1468 text = file(filename, 'rb').read()
1468 text = file(filename, 'rb').read()
1469 except IOError:
1469 except IOError:
1470 raise util.Abort(_("unable to read %s") % patchname)
1470 raise util.Abort(_("unable to read %s") % patchname)
1471 if not patchname:
1471 if not patchname:
1472 patchname = normname(os.path.basename(filename))
1472 patchname = normname(os.path.basename(filename))
1473 self.check_reserved_name(patchname)
1473 self.check_reserved_name(patchname)
1474 checkfile(patchname)
1474 checkfile(patchname)
1475 patchf = self.opener(patchname, "w")
1475 patchf = self.opener(patchname, "w")
1476 patchf.write(text)
1476 patchf.write(text)
1477 checkseries(patchname)
1477 checkseries(patchname)
1478 index = self.full_series_end() + i
1478 index = self.full_series_end() + i
1479 self.full_series[index:index] = [patchname]
1479 self.full_series[index:index] = [patchname]
1480 self.parse_series()
1480 self.parse_series()
1481 self.ui.warn("adding %s to series file\n" % patchname)
1481 self.ui.warn("adding %s to series file\n" % patchname)
1482 i += 1
1482 i += 1
1483 added.append(patchname)
1483 added.append(patchname)
1484 patchname = None
1484 patchname = None
1485 self.series_dirty = 1
1485 self.series_dirty = 1
1486 qrepo = self.qrepo()
1486 qrepo = self.qrepo()
1487 if qrepo:
1487 if qrepo:
1488 qrepo.add(added)
1488 qrepo.add(added)
1489
1489
1490 def delete(ui, repo, *patches, **opts):
1490 def delete(ui, repo, *patches, **opts):
1491 """remove patches from queue
1491 """remove patches from queue
1492
1492
1493 The patches must not be applied, unless they are arguments to
1493 The patches must not be applied, unless they are arguments to
1494 the --rev parameter. At least one patch or revision is required.
1494 the --rev parameter. At least one patch or revision is required.
1495
1495
1496 With --rev, mq will stop managing the named revisions (converting
1496 With --rev, mq will stop managing the named revisions (converting
1497 them to regular mercurial changesets). The patches must be applied
1497 them to regular mercurial changesets). The patches must be applied
1498 and at the base of the stack. This option is useful when the patches
1498 and at the base of the stack. This option is useful when the patches
1499 have been applied upstream.
1499 have been applied upstream.
1500
1500
1501 With --keep, the patch files are preserved in the patch directory."""
1501 With --keep, the patch files are preserved in the patch directory."""
1502 q = repo.mq
1502 q = repo.mq
1503 q.delete(repo, patches, opts)
1503 q.delete(repo, patches, opts)
1504 q.save_dirty()
1504 q.save_dirty()
1505 return 0
1505 return 0
1506
1506
1507 def applied(ui, repo, patch=None, **opts):
1507 def applied(ui, repo, patch=None, **opts):
1508 """print the patches already applied"""
1508 """print the patches already applied"""
1509 q = repo.mq
1509 q = repo.mq
1510 if patch:
1510 if patch:
1511 if patch not in q.series:
1511 if patch not in q.series:
1512 raise util.Abort(_("patch %s is not in series file") % patch)
1512 raise util.Abort(_("patch %s is not in series file") % patch)
1513 end = q.series.index(patch) + 1
1513 end = q.series.index(patch) + 1
1514 else:
1514 else:
1515 end = q.series_end(True)
1515 end = q.series_end(True)
1516 return q.qseries(repo, length=end, status='A', summary=opts.get('summary'))
1516 return q.qseries(repo, length=end, status='A', summary=opts.get('summary'))
1517
1517
1518 def unapplied(ui, repo, patch=None, **opts):
1518 def unapplied(ui, repo, patch=None, **opts):
1519 """print the patches not yet applied"""
1519 """print the patches not yet applied"""
1520 q = repo.mq
1520 q = repo.mq
1521 if patch:
1521 if patch:
1522 if patch not in q.series:
1522 if patch not in q.series:
1523 raise util.Abort(_("patch %s is not in series file") % patch)
1523 raise util.Abort(_("patch %s is not in series file") % patch)
1524 start = q.series.index(patch) + 1
1524 start = q.series.index(patch) + 1
1525 else:
1525 else:
1526 start = q.series_end(True)
1526 start = q.series_end(True)
1527 q.qseries(repo, start=start, status='U', summary=opts.get('summary'))
1527 q.qseries(repo, start=start, status='U', summary=opts.get('summary'))
1528
1528
1529 def qimport(ui, repo, *filename, **opts):
1529 def qimport(ui, repo, *filename, **opts):
1530 """import a patch
1530 """import a patch
1531
1531
1532 The patch will have the same name as its source file unless you
1532 The patch will have the same name as its source file unless you
1533 give it a new one with --name.
1533 give it a new one with --name.
1534
1534
1535 You can register an existing patch inside the patch directory
1535 You can register an existing patch inside the patch directory
1536 with the --existing flag.
1536 with the --existing flag.
1537
1537
1538 With --force, an existing patch of the same name will be overwritten.
1538 With --force, an existing patch of the same name will be overwritten.
1539
1539
1540 An existing changeset may be placed under mq control with --rev
1540 An existing changeset may be placed under mq control with --rev
1541 (e.g. qimport --rev tip -n patch will place tip under mq control).
1541 (e.g. qimport --rev tip -n patch will place tip under mq control).
1542 With --git, patches imported with --rev will use the git diff
1542 With --git, patches imported with --rev will use the git diff
1543 format.
1543 format.
1544 """
1544 """
1545 q = repo.mq
1545 q = repo.mq
1546 q.qimport(repo, filename, patchname=opts['name'],
1546 q.qimport(repo, filename, patchname=opts['name'],
1547 existing=opts['existing'], force=opts['force'], rev=opts['rev'],
1547 existing=opts['existing'], force=opts['force'], rev=opts['rev'],
1548 git=opts['git'])
1548 git=opts['git'])
1549 q.save_dirty()
1549 q.save_dirty()
1550 return 0
1550 return 0
1551
1551
1552 def init(ui, repo, **opts):
1552 def init(ui, repo, **opts):
1553 """init a new queue repository
1553 """init a new queue repository
1554
1554
1555 The queue repository is unversioned by default. If -c is
1555 The queue repository is unversioned by default. If -c is
1556 specified, qinit will create a separate nested repository
1556 specified, qinit will create a separate nested repository
1557 for patches (qinit -c may also be run later to convert
1557 for patches (qinit -c may also be run later to convert
1558 an unversioned patch repository into a versioned one).
1558 an unversioned patch repository into a versioned one).
1559 You can use qcommit to commit changes to this queue repository."""
1559 You can use qcommit to commit changes to this queue repository."""
1560 q = repo.mq
1560 q = repo.mq
1561 r = q.init(repo, create=opts['create_repo'])
1561 r = q.init(repo, create=opts['create_repo'])
1562 q.save_dirty()
1562 q.save_dirty()
1563 if r:
1563 if r:
1564 if not os.path.exists(r.wjoin('.hgignore')):
1564 if not os.path.exists(r.wjoin('.hgignore')):
1565 fp = r.wopener('.hgignore', 'w')
1565 fp = r.wopener('.hgignore', 'w')
1566 fp.write('^\\.hg\n')
1566 fp.write('^\\.hg\n')
1567 fp.write('^\\.mq\n')
1567 fp.write('^\\.mq\n')
1568 fp.write('syntax: glob\n')
1568 fp.write('syntax: glob\n')
1569 fp.write('status\n')
1569 fp.write('status\n')
1570 fp.write('guards\n')
1570 fp.write('guards\n')
1571 fp.close()
1571 fp.close()
1572 if not os.path.exists(r.wjoin('series')):
1572 if not os.path.exists(r.wjoin('series')):
1573 r.wopener('series', 'w').close()
1573 r.wopener('series', 'w').close()
1574 r.add(['.hgignore', 'series'])
1574 r.add(['.hgignore', 'series'])
1575 commands.add(ui, r)
1575 commands.add(ui, r)
1576 return 0
1576 return 0
1577
1577
1578 def clone(ui, source, dest=None, **opts):
1578 def clone(ui, source, dest=None, **opts):
1579 '''clone main and patch repository at same time
1579 '''clone main and patch repository at same time
1580
1580
1581 If source is local, destination will have no patches applied. If
1581 If source is local, destination will have no patches applied. If
1582 source is remote, this command can not check if patches are
1582 source is remote, this command can not check if patches are
1583 applied in source, so cannot guarantee that patches are not
1583 applied in source, so cannot guarantee that patches are not
1584 applied in destination. If you clone remote repository, be sure
1584 applied in destination. If you clone remote repository, be sure
1585 before that it has no patches applied.
1585 before that it has no patches applied.
1586
1586
1587 Source patch repository is looked for in <src>/.hg/patches by
1587 Source patch repository is looked for in <src>/.hg/patches by
1588 default. Use -p <url> to change.
1588 default. Use -p <url> to change.
1589
1589
1590 The patch directory must be a nested mercurial repository, as
1590 The patch directory must be a nested mercurial repository, as
1591 would be created by qinit -c.
1591 would be created by qinit -c.
1592 '''
1592 '''
1593 def patchdir(repo):
1593 def patchdir(repo):
1594 url = repo.url()
1594 url = repo.url()
1595 if url.endswith('/'):
1595 if url.endswith('/'):
1596 url = url[:-1]
1596 url = url[:-1]
1597 return url + '/.hg/patches'
1597 return url + '/.hg/patches'
1598 cmdutil.setremoteconfig(ui, opts)
1598 cmdutil.setremoteconfig(ui, opts)
1599 if dest is None:
1599 if dest is None:
1600 dest = hg.defaultdest(source)
1600 dest = hg.defaultdest(source)
1601 sr = hg.repository(ui, ui.expandpath(source))
1601 sr = hg.repository(ui, ui.expandpath(source))
1602 patchespath = opts['patches'] or patchdir(sr)
1602 patchespath = opts['patches'] or patchdir(sr)
1603 try:
1603 try:
1604 pr = hg.repository(ui, patchespath)
1604 pr = hg.repository(ui, patchespath)
1605 except RepoError:
1605 except RepoError:
1606 raise util.Abort(_('versioned patch repository not found'
1606 raise util.Abort(_('versioned patch repository not found'
1607 ' (see qinit -c)'))
1607 ' (see qinit -c)'))
1608 qbase, destrev = None, None
1608 qbase, destrev = None, None
1609 if sr.local():
1609 if sr.local():
1610 if sr.mq.applied:
1610 if sr.mq.applied:
1611 qbase = revlog.bin(sr.mq.applied[0].rev)
1611 qbase = revlog.bin(sr.mq.applied[0].rev)
1612 if not hg.islocal(dest):
1612 if not hg.islocal(dest):
1613 heads = dict.fromkeys(sr.heads())
1613 heads = dict.fromkeys(sr.heads())
1614 for h in sr.heads(qbase):
1614 for h in sr.heads(qbase):
1615 del heads[h]
1615 del heads[h]
1616 destrev = heads.keys()
1616 destrev = heads.keys()
1617 destrev.append(sr.changelog.parents(qbase)[0])
1617 destrev.append(sr.changelog.parents(qbase)[0])
1618 elif sr.capable('lookup'):
1618 elif sr.capable('lookup'):
1619 try:
1619 try:
1620 qbase = sr.lookup('qbase')
1620 qbase = sr.lookup('qbase')
1621 except RepoError:
1621 except RepoError:
1622 pass
1622 pass
1623 ui.note(_('cloning main repo\n'))
1623 ui.note(_('cloning main repo\n'))
1624 sr, dr = hg.clone(ui, sr.url(), dest,
1624 sr, dr = hg.clone(ui, sr.url(), dest,
1625 pull=opts['pull'],
1625 pull=opts['pull'],
1626 rev=destrev,
1626 rev=destrev,
1627 update=False,
1627 update=False,
1628 stream=opts['uncompressed'])
1628 stream=opts['uncompressed'])
1629 ui.note(_('cloning patch repo\n'))
1629 ui.note(_('cloning patch repo\n'))
1630 spr, dpr = hg.clone(ui, opts['patches'] or patchdir(sr), patchdir(dr),
1630 spr, dpr = hg.clone(ui, opts['patches'] or patchdir(sr), patchdir(dr),
1631 pull=opts['pull'], update=not opts['noupdate'],
1631 pull=opts['pull'], update=not opts['noupdate'],
1632 stream=opts['uncompressed'])
1632 stream=opts['uncompressed'])
1633 if dr.local():
1633 if dr.local():
1634 if qbase:
1634 if qbase:
1635 ui.note(_('stripping applied patches from destination repo\n'))
1635 ui.note(_('stripping applied patches from destination repo\n'))
1636 dr.mq.strip(dr, qbase, update=False, backup=None)
1636 dr.mq.strip(dr, qbase, update=False, backup=None)
1637 if not opts['noupdate']:
1637 if not opts['noupdate']:
1638 ui.note(_('updating destination repo\n'))
1638 ui.note(_('updating destination repo\n'))
1639 hg.update(dr, dr.changelog.tip())
1639 hg.update(dr, dr.changelog.tip())
1640
1640
1641 def commit(ui, repo, *pats, **opts):
1641 def commit(ui, repo, *pats, **opts):
1642 """commit changes in the queue repository"""
1642 """commit changes in the queue repository"""
1643 q = repo.mq
1643 q = repo.mq
1644 r = q.qrepo()
1644 r = q.qrepo()
1645 if not r: raise util.Abort('no queue repository')
1645 if not r: raise util.Abort('no queue repository')
1646 commands.commit(r.ui, r, *pats, **opts)
1646 commands.commit(r.ui, r, *pats, **opts)
1647
1647
1648 def series(ui, repo, **opts):
1648 def series(ui, repo, **opts):
1649 """print the entire series file"""
1649 """print the entire series file"""
1650 repo.mq.qseries(repo, missing=opts['missing'], summary=opts['summary'])
1650 repo.mq.qseries(repo, missing=opts['missing'], summary=opts['summary'])
1651 return 0
1651 return 0
1652
1652
1653 def top(ui, repo, **opts):
1653 def top(ui, repo, **opts):
1654 """print the name of the current patch"""
1654 """print the name of the current patch"""
1655 q = repo.mq
1655 q = repo.mq
1656 t = q.applied and q.series_end(True) or 0
1656 t = q.applied and q.series_end(True) or 0
1657 if t:
1657 if t:
1658 return q.qseries(repo, start=t-1, length=1, status='A',
1658 return q.qseries(repo, start=t-1, length=1, status='A',
1659 summary=opts.get('summary'))
1659 summary=opts.get('summary'))
1660 else:
1660 else:
1661 ui.write("No patches applied\n")
1661 ui.write("No patches applied\n")
1662 return 1
1662 return 1
1663
1663
1664 def next(ui, repo, **opts):
1664 def next(ui, repo, **opts):
1665 """print the name of the next patch"""
1665 """print the name of the next patch"""
1666 q = repo.mq
1666 q = repo.mq
1667 end = q.series_end()
1667 end = q.series_end()
1668 if end == len(q.series):
1668 if end == len(q.series):
1669 ui.write("All patches applied\n")
1669 ui.write("All patches applied\n")
1670 return 1
1670 return 1
1671 return q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
1671 return q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
1672
1672
1673 def prev(ui, repo, **opts):
1673 def prev(ui, repo, **opts):
1674 """print the name of the previous patch"""
1674 """print the name of the previous patch"""
1675 q = repo.mq
1675 q = repo.mq
1676 l = len(q.applied)
1676 l = len(q.applied)
1677 if l == 1:
1677 if l == 1:
1678 ui.write("Only one patch applied\n")
1678 ui.write("Only one patch applied\n")
1679 return 1
1679 return 1
1680 if not l:
1680 if not l:
1681 ui.write("No patches applied\n")
1681 ui.write("No patches applied\n")
1682 return 1
1682 return 1
1683 return q.qseries(repo, start=l-2, length=1, status='A',
1683 return q.qseries(repo, start=l-2, length=1, status='A',
1684 summary=opts.get('summary'))
1684 summary=opts.get('summary'))
1685
1685
1686 def setupheaderopts(ui, opts):
1686 def setupheaderopts(ui, opts):
1687 def do(opt,val):
1687 def do(opt,val):
1688 if not opts[opt] and opts['current' + opt]:
1688 if not opts[opt] and opts['current' + opt]:
1689 opts[opt] = val
1689 opts[opt] = val
1690 do('user', ui.username())
1690 do('user', ui.username())
1691 do('date', "%d %d" % util.makedate())
1691 do('date', "%d %d" % util.makedate())
1692
1692
1693 def new(ui, repo, patch, *args, **opts):
1693 def new(ui, repo, patch, *args, **opts):
1694 """create a new patch
1694 """create a new patch
1695
1695
1696 qnew creates a new patch on top of the currently-applied patch
1696 qnew creates a new patch on top of the currently-applied patch
1697 (if any). It will refuse to run if there are any outstanding
1697 (if any). It will refuse to run if there are any outstanding
1698 changes unless -f is specified, in which case the patch will
1698 changes unless -f is specified, in which case the patch will
1699 be initialised with them. You may also use -I, -X, and/or a list of
1699 be initialised with them. You may also use -I, -X, and/or a list of
1700 files after the patch name to add only changes to matching files
1700 files after the patch name to add only changes to matching files
1701 to the new patch, leaving the rest as uncommitted modifications.
1701 to the new patch, leaving the rest as uncommitted modifications.
1702
1702
1703 -e, -m or -l set the patch header as well as the commit message.
1703 -e, -m or -l set the patch header as well as the commit message.
1704 If none is specified, the patch header is empty and the
1704 If none is specified, the patch header is empty and the
1705 commit message is '[mq]: PATCH'"""
1705 commit message is '[mq]: PATCH'"""
1706 q = repo.mq
1706 q = repo.mq
1707 message = cmdutil.logmessage(opts)
1707 message = cmdutil.logmessage(opts)
1708 if opts['edit']:
1708 if opts['edit']:
1709 message = ui.edit(message, ui.username())
1709 message = ui.edit(message, ui.username())
1710 opts['msg'] = message
1710 opts['msg'] = message
1711 setupheaderopts(ui, opts)
1711 setupheaderopts(ui, opts)
1712 q.new(repo, patch, *args, **opts)
1712 q.new(repo, patch, *args, **opts)
1713 q.save_dirty()
1713 q.save_dirty()
1714 return 0
1714 return 0
1715
1715
1716 def refresh(ui, repo, *pats, **opts):
1716 def refresh(ui, repo, *pats, **opts):
1717 """update the current patch
1717 """update the current patch
1718
1718
1719 If any file patterns are provided, the refreshed patch will contain only
1719 If any file patterns are provided, the refreshed patch will contain only
1720 the modifications that match those patterns; the remaining modifications
1720 the modifications that match those patterns; the remaining modifications
1721 will remain in the working directory.
1721 will remain in the working directory.
1722
1722
1723 hg add/remove/copy/rename work as usual, though you might want to use
1723 hg add/remove/copy/rename work as usual, though you might want to use
1724 git-style patches (--git or [diff] git=1) to track copies and renames.
1724 git-style patches (--git or [diff] git=1) to track copies and renames.
1725 """
1725 """
1726 q = repo.mq
1726 q = repo.mq
1727 message = cmdutil.logmessage(opts)
1727 message = cmdutil.logmessage(opts)
1728 if opts['edit']:
1728 if opts['edit']:
1729 if not q.applied:
1729 if not q.applied:
1730 ui.write(_("No patches applied\n"))
1730 ui.write(_("No patches applied\n"))
1731 return 1
1731 return 1
1732 if message:
1732 if message:
1733 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
1733 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
1734 patch = q.applied[-1].name
1734 patch = q.applied[-1].name
1735 (message, comment, user, date, hasdiff) = q.readheaders(patch)
1735 (message, comment, user, date, hasdiff) = q.readheaders(patch)
1736 message = ui.edit('\n'.join(message), user or ui.username())
1736 message = ui.edit('\n'.join(message), user or ui.username())
1737 setupheaderopts(ui, opts)
1737 setupheaderopts(ui, opts)
1738 ret = q.refresh(repo, pats, msg=message, **opts)
1738 ret = q.refresh(repo, pats, msg=message, **opts)
1739 q.save_dirty()
1739 q.save_dirty()
1740 return ret
1740 return ret
1741
1741
1742 def diff(ui, repo, *pats, **opts):
1742 def diff(ui, repo, *pats, **opts):
1743 """diff of the current patch"""
1743 """diff of the current patch"""
1744 repo.mq.diff(repo, pats, opts)
1744 repo.mq.diff(repo, pats, opts)
1745 return 0
1745 return 0
1746
1746
1747 def fold(ui, repo, *files, **opts):
1747 def fold(ui, repo, *files, **opts):
1748 """fold the named patches into the current patch
1748 """fold the named patches into the current patch
1749
1749
1750 Patches must not yet be applied. Each patch will be successively
1750 Patches must not yet be applied. Each patch will be successively
1751 applied to the current patch in the order given. If all the
1751 applied to the current patch in the order given. If all the
1752 patches apply successfully, the current patch will be refreshed
1752 patches apply successfully, the current patch will be refreshed
1753 with the new cumulative patch, and the folded patches will
1753 with the new cumulative patch, and the folded patches will
1754 be deleted. With -k/--keep, the folded patch files will not
1754 be deleted. With -k/--keep, the folded patch files will not
1755 be removed afterwards.
1755 be removed afterwards.
1756
1756
1757 The header for each folded patch will be concatenated with
1757 The header for each folded patch will be concatenated with
1758 the current patch header, separated by a line of '* * *'."""
1758 the current patch header, separated by a line of '* * *'."""
1759
1759
1760 q = repo.mq
1760 q = repo.mq
1761
1761
1762 if not files:
1762 if not files:
1763 raise util.Abort(_('qfold requires at least one patch name'))
1763 raise util.Abort(_('qfold requires at least one patch name'))
1764 if not q.check_toppatch(repo):
1764 if not q.check_toppatch(repo):
1765 raise util.Abort(_('No patches applied'))
1765 raise util.Abort(_('No patches applied'))
1766
1766
1767 message = cmdutil.logmessage(opts)
1767 message = cmdutil.logmessage(opts)
1768 if opts['edit']:
1768 if opts['edit']:
1769 if message:
1769 if message:
1770 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
1770 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
1771
1771
1772 parent = q.lookup('qtip')
1772 parent = q.lookup('qtip')
1773 patches = []
1773 patches = []
1774 messages = []
1774 messages = []
1775 for f in files:
1775 for f in files:
1776 p = q.lookup(f)
1776 p = q.lookup(f)
1777 if p in patches or p == parent:
1777 if p in patches or p == parent:
1778 ui.warn(_('Skipping already folded patch %s') % p)
1778 ui.warn(_('Skipping already folded patch %s') % p)
1779 if q.isapplied(p):
1779 if q.isapplied(p):
1780 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
1780 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
1781 patches.append(p)
1781 patches.append(p)
1782
1782
1783 for p in patches:
1783 for p in patches:
1784 if not message:
1784 if not message:
1785 messages.append(q.readheaders(p)[0])
1785 messages.append(q.readheaders(p)[0])
1786 pf = q.join(p)
1786 pf = q.join(p)
1787 (patchsuccess, files, fuzz) = q.patch(repo, pf)
1787 (patchsuccess, files, fuzz) = q.patch(repo, pf)
1788 if not patchsuccess:
1788 if not patchsuccess:
1789 raise util.Abort(_('Error folding patch %s') % p)
1789 raise util.Abort(_('Error folding patch %s') % p)
1790 patch.updatedir(ui, repo, files)
1790 patch.updatedir(ui, repo, files)
1791
1791
1792 if not message:
1792 if not message:
1793 message, comments, user = q.readheaders(parent)[0:3]
1793 message, comments, user = q.readheaders(parent)[0:3]
1794 for msg in messages:
1794 for msg in messages:
1795 message.append('* * *')
1795 message.append('* * *')
1796 message.extend(msg)
1796 message.extend(msg)
1797 message = '\n'.join(message)
1797 message = '\n'.join(message)
1798
1798
1799 if opts['edit']:
1799 if opts['edit']:
1800 message = ui.edit(message, user or ui.username())
1800 message = ui.edit(message, user or ui.username())
1801
1801
1802 q.refresh(repo, msg=message)
1802 q.refresh(repo, msg=message)
1803 q.delete(repo, patches, opts)
1803 q.delete(repo, patches, opts)
1804 q.save_dirty()
1804 q.save_dirty()
1805
1805
1806 def goto(ui, repo, patch, **opts):
1806 def goto(ui, repo, patch, **opts):
1807 '''push or pop patches until named patch is at top of stack'''
1807 '''push or pop patches until named patch is at top of stack'''
1808 q = repo.mq
1808 q = repo.mq
1809 patch = q.lookup(patch)
1809 patch = q.lookup(patch)
1810 if q.isapplied(patch):
1810 if q.isapplied(patch):
1811 ret = q.pop(repo, patch, force=opts['force'])
1811 ret = q.pop(repo, patch, force=opts['force'])
1812 else:
1812 else:
1813 ret = q.push(repo, patch, force=opts['force'])
1813 ret = q.push(repo, patch, force=opts['force'])
1814 q.save_dirty()
1814 q.save_dirty()
1815 return ret
1815 return ret
1816
1816
1817 def guard(ui, repo, *args, **opts):
1817 def guard(ui, repo, *args, **opts):
1818 '''set or print guards for a patch
1818 '''set or print guards for a patch
1819
1819
1820 Guards control whether a patch can be pushed. A patch with no
1820 Guards control whether a patch can be pushed. A patch with no
1821 guards is always pushed. A patch with a positive guard ("+foo") is
1821 guards is always pushed. A patch with a positive guard ("+foo") is
1822 pushed only if the qselect command has activated it. A patch with
1822 pushed only if the qselect command has activated it. A patch with
1823 a negative guard ("-foo") is never pushed if the qselect command
1823 a negative guard ("-foo") is never pushed if the qselect command
1824 has activated it.
1824 has activated it.
1825
1825
1826 With no arguments, print the currently active guards.
1826 With no arguments, print the currently active guards.
1827 With arguments, set guards for the named patch.
1827 With arguments, set guards for the named patch.
1828
1828
1829 To set a negative guard "-foo" on topmost patch ("--" is needed so
1829 To set a negative guard "-foo" on topmost patch ("--" is needed so
1830 hg will not interpret "-foo" as an option):
1830 hg will not interpret "-foo" as an option):
1831 hg qguard -- -foo
1831 hg qguard -- -foo
1832
1832
1833 To set guards on another patch:
1833 To set guards on another patch:
1834 hg qguard other.patch +2.6.17 -stable
1834 hg qguard other.patch +2.6.17 -stable
1835 '''
1835 '''
1836 def status(idx):
1836 def status(idx):
1837 guards = q.series_guards[idx] or ['unguarded']
1837 guards = q.series_guards[idx] or ['unguarded']
1838 ui.write('%s: %s\n' % (q.series[idx], ' '.join(guards)))
1838 ui.write('%s: %s\n' % (q.series[idx], ' '.join(guards)))
1839 q = repo.mq
1839 q = repo.mq
1840 patch = None
1840 patch = None
1841 args = list(args)
1841 args = list(args)
1842 if opts['list']:
1842 if opts['list']:
1843 if args or opts['none']:
1843 if args or opts['none']:
1844 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
1844 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
1845 for i in xrange(len(q.series)):
1845 for i in xrange(len(q.series)):
1846 status(i)
1846 status(i)
1847 return
1847 return
1848 if not args or args[0][0:1] in '-+':
1848 if not args or args[0][0:1] in '-+':
1849 if not q.applied:
1849 if not q.applied:
1850 raise util.Abort(_('no patches applied'))
1850 raise util.Abort(_('no patches applied'))
1851 patch = q.applied[-1].name
1851 patch = q.applied[-1].name
1852 if patch is None and args[0][0:1] not in '-+':
1852 if patch is None and args[0][0:1] not in '-+':
1853 patch = args.pop(0)
1853 patch = args.pop(0)
1854 if patch is None:
1854 if patch is None:
1855 raise util.Abort(_('no patch to work with'))
1855 raise util.Abort(_('no patch to work with'))
1856 if args or opts['none']:
1856 if args or opts['none']:
1857 idx = q.find_series(patch)
1857 idx = q.find_series(patch)
1858 if idx is None:
1858 if idx is None:
1859 raise util.Abort(_('no patch named %s') % patch)
1859 raise util.Abort(_('no patch named %s') % patch)
1860 q.set_guards(idx, args)
1860 q.set_guards(idx, args)
1861 q.save_dirty()
1861 q.save_dirty()
1862 else:
1862 else:
1863 status(q.series.index(q.lookup(patch)))
1863 status(q.series.index(q.lookup(patch)))
1864
1864
1865 def header(ui, repo, patch=None):
1865 def header(ui, repo, patch=None):
1866 """Print the header of the topmost or specified patch"""
1866 """Print the header of the topmost or specified patch"""
1867 q = repo.mq
1867 q = repo.mq
1868
1868
1869 if patch:
1869 if patch:
1870 patch = q.lookup(patch)
1870 patch = q.lookup(patch)
1871 else:
1871 else:
1872 if not q.applied:
1872 if not q.applied:
1873 ui.write('No patches applied\n')
1873 ui.write('No patches applied\n')
1874 return 1
1874 return 1
1875 patch = q.lookup('qtip')
1875 patch = q.lookup('qtip')
1876 message = repo.mq.readheaders(patch)[0]
1876 message = repo.mq.readheaders(patch)[0]
1877
1877
1878 ui.write('\n'.join(message) + '\n')
1878 ui.write('\n'.join(message) + '\n')
1879
1879
1880 def lastsavename(path):
1880 def lastsavename(path):
1881 (directory, base) = os.path.split(path)
1881 (directory, base) = os.path.split(path)
1882 names = os.listdir(directory)
1882 names = os.listdir(directory)
1883 namere = re.compile("%s.([0-9]+)" % base)
1883 namere = re.compile("%s.([0-9]+)" % base)
1884 maxindex = None
1884 maxindex = None
1885 maxname = None
1885 maxname = None
1886 for f in names:
1886 for f in names:
1887 m = namere.match(f)
1887 m = namere.match(f)
1888 if m:
1888 if m:
1889 index = int(m.group(1))
1889 index = int(m.group(1))
1890 if maxindex == None or index > maxindex:
1890 if maxindex == None or index > maxindex:
1891 maxindex = index
1891 maxindex = index
1892 maxname = f
1892 maxname = f
1893 if maxname:
1893 if maxname:
1894 return (os.path.join(directory, maxname), maxindex)
1894 return (os.path.join(directory, maxname), maxindex)
1895 return (None, None)
1895 return (None, None)
1896
1896
1897 def savename(path):
1897 def savename(path):
1898 (last, index) = lastsavename(path)
1898 (last, index) = lastsavename(path)
1899 if last is None:
1899 if last is None:
1900 index = 0
1900 index = 0
1901 newpath = path + ".%d" % (index + 1)
1901 newpath = path + ".%d" % (index + 1)
1902 return newpath
1902 return newpath
1903
1903
1904 def push(ui, repo, patch=None, **opts):
1904 def push(ui, repo, patch=None, **opts):
1905 """push the next patch onto the stack
1905 """push the next patch onto the stack
1906
1906
1907 When --force is applied, all local changes in patched files will be lost.
1907 When --force is applied, all local changes in patched files will be lost.
1908 """
1908 """
1909 q = repo.mq
1909 q = repo.mq
1910 mergeq = None
1910 mergeq = None
1911
1911
1912 if opts['all']:
1912 if opts['all']:
1913 if not q.series:
1913 if not q.series:
1914 ui.warn(_('no patches in series\n'))
1914 ui.warn(_('no patches in series\n'))
1915 return 0
1915 return 0
1916 patch = q.series[-1]
1916 patch = q.series[-1]
1917 if opts['merge']:
1917 if opts['merge']:
1918 if opts['name']:
1918 if opts['name']:
1919 newpath = opts['name']
1919 newpath = opts['name']
1920 else:
1920 else:
1921 newpath, i = lastsavename(q.path)
1921 newpath, i = lastsavename(q.path)
1922 if not newpath:
1922 if not newpath:
1923 ui.warn("no saved queues found, please use -n\n")
1923 ui.warn("no saved queues found, please use -n\n")
1924 return 1
1924 return 1
1925 mergeq = queue(ui, repo.join(""), newpath)
1925 mergeq = queue(ui, repo.join(""), newpath)
1926 ui.warn("merging with queue at: %s\n" % mergeq.path)
1926 ui.warn("merging with queue at: %s\n" % mergeq.path)
1927 ret = q.push(repo, patch, force=opts['force'], list=opts['list'],
1927 ret = q.push(repo, patch, force=opts['force'], list=opts['list'],
1928 mergeq=mergeq)
1928 mergeq=mergeq)
1929 return ret
1929 return ret
1930
1930
1931 def pop(ui, repo, patch=None, **opts):
1931 def pop(ui, repo, patch=None, **opts):
1932 """pop the current patch off the stack"""
1932 """pop the current patch off the stack"""
1933 localupdate = True
1933 localupdate = True
1934 if opts['name']:
1934 if opts['name']:
1935 q = queue(ui, repo.join(""), repo.join(opts['name']))
1935 q = queue(ui, repo.join(""), repo.join(opts['name']))
1936 ui.warn('using patch queue: %s\n' % q.path)
1936 ui.warn('using patch queue: %s\n' % q.path)
1937 localupdate = False
1937 localupdate = False
1938 else:
1938 else:
1939 q = repo.mq
1939 q = repo.mq
1940 ret = q.pop(repo, patch, force=opts['force'], update=localupdate,
1940 ret = q.pop(repo, patch, force=opts['force'], update=localupdate,
1941 all=opts['all'])
1941 all=opts['all'])
1942 q.save_dirty()
1942 q.save_dirty()
1943 return ret
1943 return ret
1944
1944
1945 def rename(ui, repo, patch, name=None, **opts):
1945 def rename(ui, repo, patch, name=None, **opts):
1946 """rename a patch
1946 """rename a patch
1947
1947
1948 With one argument, renames the current patch to PATCH1.
1948 With one argument, renames the current patch to PATCH1.
1949 With two arguments, renames PATCH1 to PATCH2."""
1949 With two arguments, renames PATCH1 to PATCH2."""
1950
1950
1951 q = repo.mq
1951 q = repo.mq
1952
1952
1953 if not name:
1953 if not name:
1954 name = patch
1954 name = patch
1955 patch = None
1955 patch = None
1956
1956
1957 if patch:
1957 if patch:
1958 patch = q.lookup(patch)
1958 patch = q.lookup(patch)
1959 else:
1959 else:
1960 if not q.applied:
1960 if not q.applied:
1961 ui.write(_('No patches applied\n'))
1961 ui.write(_('No patches applied\n'))
1962 return
1962 return
1963 patch = q.lookup('qtip')
1963 patch = q.lookup('qtip')
1964 absdest = q.join(name)
1964 absdest = q.join(name)
1965 if os.path.isdir(absdest):
1965 if os.path.isdir(absdest):
1966 name = normname(os.path.join(name, os.path.basename(patch)))
1966 name = normname(os.path.join(name, os.path.basename(patch)))
1967 absdest = q.join(name)
1967 absdest = q.join(name)
1968 if os.path.exists(absdest):
1968 if os.path.exists(absdest):
1969 raise util.Abort(_('%s already exists') % absdest)
1969 raise util.Abort(_('%s already exists') % absdest)
1970
1970
1971 if name in q.series:
1971 if name in q.series:
1972 raise util.Abort(_('A patch named %s already exists in the series file') % name)
1972 raise util.Abort(_('A patch named %s already exists in the series file') % name)
1973
1973
1974 if ui.verbose:
1974 if ui.verbose:
1975 ui.write('Renaming %s to %s\n' % (patch, name))
1975 ui.write('Renaming %s to %s\n' % (patch, name))
1976 i = q.find_series(patch)
1976 i = q.find_series(patch)
1977 guards = q.guard_re.findall(q.full_series[i])
1977 guards = q.guard_re.findall(q.full_series[i])
1978 q.full_series[i] = name + ''.join([' #' + g for g in guards])
1978 q.full_series[i] = name + ''.join([' #' + g for g in guards])
1979 q.parse_series()
1979 q.parse_series()
1980 q.series_dirty = 1
1980 q.series_dirty = 1
1981
1981
1982 info = q.isapplied(patch)
1982 info = q.isapplied(patch)
1983 if info:
1983 if info:
1984 q.applied[info[0]] = statusentry(info[1], name)
1984 q.applied[info[0]] = statusentry(info[1], name)
1985 q.applied_dirty = 1
1985 q.applied_dirty = 1
1986
1986
1987 util.rename(q.join(patch), absdest)
1987 util.rename(q.join(patch), absdest)
1988 r = q.qrepo()
1988 r = q.qrepo()
1989 if r:
1989 if r:
1990 wlock = r.wlock()
1990 wlock = r.wlock()
1991 try:
1991 try:
1992 if r.dirstate[name] == 'r':
1992 if r.dirstate[name] == 'r':
1993 r.undelete([name])
1993 r.undelete([name])
1994 r.copy(patch, name)
1994 r.copy(patch, name)
1995 r.remove([patch], False)
1995 r.remove([patch], False)
1996 finally:
1996 finally:
1997 del wlock
1997 del wlock
1998
1998
1999 q.save_dirty()
1999 q.save_dirty()
2000
2000
2001 def restore(ui, repo, rev, **opts):
2001 def restore(ui, repo, rev, **opts):
2002 """restore the queue state saved by a rev"""
2002 """restore the queue state saved by a rev"""
2003 rev = repo.lookup(rev)
2003 rev = repo.lookup(rev)
2004 q = repo.mq
2004 q = repo.mq
2005 q.restore(repo, rev, delete=opts['delete'],
2005 q.restore(repo, rev, delete=opts['delete'],
2006 qupdate=opts['update'])
2006 qupdate=opts['update'])
2007 q.save_dirty()
2007 q.save_dirty()
2008 return 0
2008 return 0
2009
2009
2010 def save(ui, repo, **opts):
2010 def save(ui, repo, **opts):
2011 """save current queue state"""
2011 """save current queue state"""
2012 q = repo.mq
2012 q = repo.mq
2013 message = cmdutil.logmessage(opts)
2013 message = cmdutil.logmessage(opts)
2014 ret = q.save(repo, msg=message)
2014 ret = q.save(repo, msg=message)
2015 if ret:
2015 if ret:
2016 return ret
2016 return ret
2017 q.save_dirty()
2017 q.save_dirty()
2018 if opts['copy']:
2018 if opts['copy']:
2019 path = q.path
2019 path = q.path
2020 if opts['name']:
2020 if opts['name']:
2021 newpath = os.path.join(q.basepath, opts['name'])
2021 newpath = os.path.join(q.basepath, opts['name'])
2022 if os.path.exists(newpath):
2022 if os.path.exists(newpath):
2023 if not os.path.isdir(newpath):
2023 if not os.path.isdir(newpath):
2024 raise util.Abort(_('destination %s exists and is not '
2024 raise util.Abort(_('destination %s exists and is not '
2025 'a directory') % newpath)
2025 'a directory') % newpath)
2026 if not opts['force']:
2026 if not opts['force']:
2027 raise util.Abort(_('destination %s exists, '
2027 raise util.Abort(_('destination %s exists, '
2028 'use -f to force') % newpath)
2028 'use -f to force') % newpath)
2029 else:
2029 else:
2030 newpath = savename(path)
2030 newpath = savename(path)
2031 ui.warn("copy %s to %s\n" % (path, newpath))
2031 ui.warn("copy %s to %s\n" % (path, newpath))
2032 util.copyfiles(path, newpath)
2032 util.copyfiles(path, newpath)
2033 if opts['empty']:
2033 if opts['empty']:
2034 try:
2034 try:
2035 os.unlink(q.join(q.status_path))
2035 os.unlink(q.join(q.status_path))
2036 except:
2036 except:
2037 pass
2037 pass
2038 return 0
2038 return 0
2039
2039
2040 def strip(ui, repo, rev, **opts):
2040 def strip(ui, repo, rev, **opts):
2041 """strip a revision and all later revs on the same branch"""
2041 """strip a revision and all later revs on the same branch"""
2042 rev = repo.lookup(rev)
2042 rev = repo.lookup(rev)
2043 backup = 'all'
2043 backup = 'all'
2044 if opts['backup']:
2044 if opts['backup']:
2045 backup = 'strip'
2045 backup = 'strip'
2046 elif opts['nobackup']:
2046 elif opts['nobackup']:
2047 backup = 'none'
2047 backup = 'none'
2048 update = repo.dirstate.parents()[0] != revlog.nullid
2048 update = repo.dirstate.parents()[0] != revlog.nullid
2049 repo.mq.strip(repo, rev, backup=backup, update=update, force=opts['force'])
2049 repo.mq.strip(repo, rev, backup=backup, update=update, force=opts['force'])
2050 return 0
2050 return 0
2051
2051
2052 def select(ui, repo, *args, **opts):
2052 def select(ui, repo, *args, **opts):
2053 '''set or print guarded patches to push
2053 '''set or print guarded patches to push
2054
2054
2055 Use the qguard command to set or print guards on patch, then use
2055 Use the qguard command to set or print guards on patch, then use
2056 qselect to tell mq which guards to use. A patch will be pushed if it
2056 qselect to tell mq which guards to use. A patch will be pushed if it
2057 has no guards or any positive guards match the currently selected guard,
2057 has no guards or any positive guards match the currently selected guard,
2058 but will not be pushed if any negative guards match the current guard.
2058 but will not be pushed if any negative guards match the current guard.
2059 For example:
2059 For example:
2060
2060
2061 qguard foo.patch -stable (negative guard)
2061 qguard foo.patch -stable (negative guard)
2062 qguard bar.patch +stable (positive guard)
2062 qguard bar.patch +stable (positive guard)
2063 qselect stable
2063 qselect stable
2064
2064
2065 This activates the "stable" guard. mq will skip foo.patch (because
2065 This activates the "stable" guard. mq will skip foo.patch (because
2066 it has a negative match) but push bar.patch (because it
2066 it has a negative match) but push bar.patch (because it
2067 has a positive match).
2067 has a positive match).
2068
2068
2069 With no arguments, prints the currently active guards.
2069 With no arguments, prints the currently active guards.
2070 With one argument, sets the active guard.
2070 With one argument, sets the active guard.
2071
2071
2072 Use -n/--none to deactivate guards (no other arguments needed).
2072 Use -n/--none to deactivate guards (no other arguments needed).
2073 When no guards are active, patches with positive guards are skipped
2073 When no guards are active, patches with positive guards are skipped
2074 and patches with negative guards are pushed.
2074 and patches with negative guards are pushed.
2075
2075
2076 qselect can change the guards on applied patches. It does not pop
2076 qselect can change the guards on applied patches. It does not pop
2077 guarded patches by default. Use --pop to pop back to the last applied
2077 guarded patches by default. Use --pop to pop back to the last applied
2078 patch that is not guarded. Use --reapply (which implies --pop) to push
2078 patch that is not guarded. Use --reapply (which implies --pop) to push
2079 back to the current patch afterwards, but skip guarded patches.
2079 back to the current patch afterwards, but skip guarded patches.
2080
2080
2081 Use -s/--series to print a list of all guards in the series file (no
2081 Use -s/--series to print a list of all guards in the series file (no
2082 other arguments needed). Use -v for more information.'''
2082 other arguments needed). Use -v for more information.'''
2083
2083
2084 q = repo.mq
2084 q = repo.mq
2085 guards = q.active()
2085 guards = q.active()
2086 if args or opts['none']:
2086 if args or opts['none']:
2087 old_unapplied = q.unapplied(repo)
2087 old_unapplied = q.unapplied(repo)
2088 old_guarded = [i for i in xrange(len(q.applied)) if
2088 old_guarded = [i for i in xrange(len(q.applied)) if
2089 not q.pushable(i)[0]]
2089 not q.pushable(i)[0]]
2090 q.set_active(args)
2090 q.set_active(args)
2091 q.save_dirty()
2091 q.save_dirty()
2092 if not args:
2092 if not args:
2093 ui.status(_('guards deactivated\n'))
2093 ui.status(_('guards deactivated\n'))
2094 if not opts['pop'] and not opts['reapply']:
2094 if not opts['pop'] and not opts['reapply']:
2095 unapplied = q.unapplied(repo)
2095 unapplied = q.unapplied(repo)
2096 guarded = [i for i in xrange(len(q.applied))
2096 guarded = [i for i in xrange(len(q.applied))
2097 if not q.pushable(i)[0]]
2097 if not q.pushable(i)[0]]
2098 if len(unapplied) != len(old_unapplied):
2098 if len(unapplied) != len(old_unapplied):
2099 ui.status(_('number of unguarded, unapplied patches has '
2099 ui.status(_('number of unguarded, unapplied patches has '
2100 'changed from %d to %d\n') %
2100 'changed from %d to %d\n') %
2101 (len(old_unapplied), len(unapplied)))
2101 (len(old_unapplied), len(unapplied)))
2102 if len(guarded) != len(old_guarded):
2102 if len(guarded) != len(old_guarded):
2103 ui.status(_('number of guarded, applied patches has changed '
2103 ui.status(_('number of guarded, applied patches has changed '
2104 'from %d to %d\n') %
2104 'from %d to %d\n') %
2105 (len(old_guarded), len(guarded)))
2105 (len(old_guarded), len(guarded)))
2106 elif opts['series']:
2106 elif opts['series']:
2107 guards = {}
2107 guards = {}
2108 noguards = 0
2108 noguards = 0
2109 for gs in q.series_guards:
2109 for gs in q.series_guards:
2110 if not gs:
2110 if not gs:
2111 noguards += 1
2111 noguards += 1
2112 for g in gs:
2112 for g in gs:
2113 guards.setdefault(g, 0)
2113 guards.setdefault(g, 0)
2114 guards[g] += 1
2114 guards[g] += 1
2115 if ui.verbose:
2115 if ui.verbose:
2116 guards['NONE'] = noguards
2116 guards['NONE'] = noguards
2117 guards = guards.items()
2117 guards = guards.items()
2118 guards.sort(lambda a, b: cmp(a[0][1:], b[0][1:]))
2118 guards.sort(lambda a, b: cmp(a[0][1:], b[0][1:]))
2119 if guards:
2119 if guards:
2120 ui.note(_('guards in series file:\n'))
2120 ui.note(_('guards in series file:\n'))
2121 for guard, count in guards:
2121 for guard, count in guards:
2122 ui.note('%2d ' % count)
2122 ui.note('%2d ' % count)
2123 ui.write(guard, '\n')
2123 ui.write(guard, '\n')
2124 else:
2124 else:
2125 ui.note(_('no guards in series file\n'))
2125 ui.note(_('no guards in series file\n'))
2126 else:
2126 else:
2127 if guards:
2127 if guards:
2128 ui.note(_('active guards:\n'))
2128 ui.note(_('active guards:\n'))
2129 for g in guards:
2129 for g in guards:
2130 ui.write(g, '\n')
2130 ui.write(g, '\n')
2131 else:
2131 else:
2132 ui.write(_('no active guards\n'))
2132 ui.write(_('no active guards\n'))
2133 reapply = opts['reapply'] and q.applied and q.appliedname(-1)
2133 reapply = opts['reapply'] and q.applied and q.appliedname(-1)
2134 popped = False
2134 popped = False
2135 if opts['pop'] or opts['reapply']:
2135 if opts['pop'] or opts['reapply']:
2136 for i in xrange(len(q.applied)):
2136 for i in xrange(len(q.applied)):
2137 pushable, reason = q.pushable(i)
2137 pushable, reason = q.pushable(i)
2138 if not pushable:
2138 if not pushable:
2139 ui.status(_('popping guarded patches\n'))
2139 ui.status(_('popping guarded patches\n'))
2140 popped = True
2140 popped = True
2141 if i == 0:
2141 if i == 0:
2142 q.pop(repo, all=True)
2142 q.pop(repo, all=True)
2143 else:
2143 else:
2144 q.pop(repo, i-1)
2144 q.pop(repo, i-1)
2145 break
2145 break
2146 if popped:
2146 if popped:
2147 try:
2147 try:
2148 if reapply:
2148 if reapply:
2149 ui.status(_('reapplying unguarded patches\n'))
2149 ui.status(_('reapplying unguarded patches\n'))
2150 q.push(repo, reapply)
2150 q.push(repo, reapply)
2151 finally:
2151 finally:
2152 q.save_dirty()
2152 q.save_dirty()
2153
2153
2154 def reposetup(ui, repo):
2154 def reposetup(ui, repo):
2155 class mqrepo(repo.__class__):
2155 class mqrepo(repo.__class__):
2156 def abort_if_wdir_patched(self, errmsg, force=False):
2156 def abort_if_wdir_patched(self, errmsg, force=False):
2157 if self.mq.applied and not force:
2157 if self.mq.applied and not force:
2158 parent = revlog.hex(self.dirstate.parents()[0])
2158 parent = revlog.hex(self.dirstate.parents()[0])
2159 if parent in [s.rev for s in self.mq.applied]:
2159 if parent in [s.rev for s in self.mq.applied]:
2160 raise util.Abort(errmsg)
2160 raise util.Abort(errmsg)
2161
2161
2162 def commit(self, *args, **opts):
2162 def commit(self, *args, **opts):
2163 if len(args) >= 6:
2163 if len(args) >= 6:
2164 force = args[5]
2164 force = args[5]
2165 else:
2165 else:
2166 force = opts.get('force')
2166 force = opts.get('force')
2167 self.abort_if_wdir_patched(
2167 self.abort_if_wdir_patched(
2168 _('cannot commit over an applied mq patch'),
2168 _('cannot commit over an applied mq patch'),
2169 force)
2169 force)
2170
2170
2171 return super(mqrepo, self).commit(*args, **opts)
2171 return super(mqrepo, self).commit(*args, **opts)
2172
2172
2173 def push(self, remote, force=False, revs=None):
2173 def push(self, remote, force=False, revs=None):
2174 if self.mq.applied and not force and not revs:
2174 if self.mq.applied and not force and not revs:
2175 raise util.Abort(_('source has mq patches applied'))
2175 raise util.Abort(_('source has mq patches applied'))
2176 return super(mqrepo, self).push(remote, force, revs)
2176 return super(mqrepo, self).push(remote, force, revs)
2177
2177
2178 def tags(self):
2178 def tags(self):
2179 if self.tagscache:
2179 if self.tagscache:
2180 return self.tagscache
2180 return self.tagscache
2181
2181
2182 tagscache = super(mqrepo, self).tags()
2182 tagscache = super(mqrepo, self).tags()
2183
2183
2184 q = self.mq
2184 q = self.mq
2185 if not q.applied:
2185 if not q.applied:
2186 return tagscache
2186 return tagscache
2187
2187
2188 mqtags = [(revlog.bin(patch.rev), patch.name) for patch in q.applied]
2188 mqtags = [(revlog.bin(patch.rev), patch.name) for patch in q.applied]
2189
2189
2190 if mqtags[-1][0] not in self.changelog.nodemap:
2190 if mqtags[-1][0] not in self.changelog.nodemap:
2191 self.ui.warn('mq status file refers to unknown node %s\n'
2191 self.ui.warn('mq status file refers to unknown node %s\n'
2192 % revlog.short(mqtags[-1][0]))
2192 % revlog.short(mqtags[-1][0]))
2193 return tagscache
2193 return tagscache
2194
2194
2195 mqtags.append((mqtags[-1][0], 'qtip'))
2195 mqtags.append((mqtags[-1][0], 'qtip'))
2196 mqtags.append((mqtags[0][0], 'qbase'))
2196 mqtags.append((mqtags[0][0], 'qbase'))
2197 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
2197 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
2198 for patch in mqtags:
2198 for patch in mqtags:
2199 if patch[1] in tagscache:
2199 if patch[1] in tagscache:
2200 self.ui.warn('Tag %s overrides mq patch of the same name\n' % patch[1])
2200 self.ui.warn('Tag %s overrides mq patch of the same name\n' % patch[1])
2201 else:
2201 else:
2202 tagscache[patch[1]] = patch[0]
2202 tagscache[patch[1]] = patch[0]
2203
2203
2204 return tagscache
2204 return tagscache
2205
2205
2206 def _branchtags(self, partial, lrev):
2206 def _branchtags(self, partial, lrev):
2207 q = self.mq
2207 q = self.mq
2208 if not q.applied:
2208 if not q.applied:
2209 return super(mqrepo, self)._branchtags(partial, lrev)
2209 return super(mqrepo, self)._branchtags(partial, lrev)
2210
2210
2211 cl = self.changelog
2211 cl = self.changelog
2212 qbasenode = revlog.bin(q.applied[0].rev)
2212 qbasenode = revlog.bin(q.applied[0].rev)
2213 if qbasenode not in cl.nodemap:
2213 if qbasenode not in cl.nodemap:
2214 self.ui.warn('mq status file refers to unknown node %s\n'
2214 self.ui.warn('mq status file refers to unknown node %s\n'
2215 % revlog.short(qbasenode))
2215 % revlog.short(qbasenode))
2216 return super(mqrepo, self)._branchtags(partial, lrev)
2216 return super(mqrepo, self)._branchtags(partial, lrev)
2217
2217
2218 qbase = cl.rev(qbasenode)
2218 qbase = cl.rev(qbasenode)
2219 start = lrev + 1
2219 start = lrev + 1
2220 if start < qbase:
2220 if start < qbase:
2221 # update the cache (excluding the patches) and save it
2221 # update the cache (excluding the patches) and save it
2222 self._updatebranchcache(partial, lrev+1, qbase)
2222 self._updatebranchcache(partial, lrev+1, qbase)
2223 self._writebranchcache(partial, cl.node(qbase-1), qbase-1)
2223 self._writebranchcache(partial, cl.node(qbase-1), qbase-1)
2224 start = qbase
2224 start = qbase
2225 # if start = qbase, the cache is as updated as it should be.
2225 # if start = qbase, the cache is as updated as it should be.
2226 # if start > qbase, the cache includes (part of) the patches.
2226 # if start > qbase, the cache includes (part of) the patches.
2227 # we might as well use it, but we won't save it.
2227 # we might as well use it, but we won't save it.
2228
2228
2229 # update the cache up to the tip
2229 # update the cache up to the tip
2230 self._updatebranchcache(partial, start, cl.count())
2230 self._updatebranchcache(partial, start, cl.count())
2231
2231
2232 return partial
2232 return partial
2233
2233
2234 if repo.local():
2234 if repo.local():
2235 repo.__class__ = mqrepo
2235 repo.__class__ = mqrepo
2236 repo.mq = queue(ui, repo.join(""))
2236 repo.mq = queue(ui, repo.join(""))
2237
2237
2238 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
2238 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
2239
2239
2240 headeropts = [
2240 headeropts = [
2241 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2241 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2242 ('u', 'user', '', _('add "From: <given user>" to patch')),
2242 ('u', 'user', '', _('add "From: <given user>" to patch')),
2243 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2243 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2244 ('d', 'date', '', _('add "Date: <given date>" to patch'))]
2244 ('d', 'date', '', _('add "Date: <given date>" to patch'))]
2245
2245
2246 cmdtable = {
2246 cmdtable = {
2247 "qapplied": (applied, [] + seriesopts, _('hg qapplied [-s] [PATCH]')),
2247 "qapplied": (applied, [] + seriesopts, _('hg qapplied [-s] [PATCH]')),
2248 "qclone":
2248 "qclone":
2249 (clone,
2249 (clone,
2250 [('', 'pull', None, _('use pull protocol to copy metadata')),
2250 [('', 'pull', None, _('use pull protocol to copy metadata')),
2251 ('U', 'noupdate', None, _('do not update the new working directories')),
2251 ('U', 'noupdate', None, _('do not update the new working directories')),
2252 ('', 'uncompressed', None,
2252 ('', 'uncompressed', None,
2253 _('use uncompressed transfer (fast over LAN)')),
2253 _('use uncompressed transfer (fast over LAN)')),
2254 ('p', 'patches', '', _('location of source patch repo')),
2254 ('p', 'patches', '', _('location of source patch repo')),
2255 ] + commands.remoteopts,
2255 ] + commands.remoteopts,
2256 _('hg qclone [OPTION]... SOURCE [DEST]')),
2256 _('hg qclone [OPTION]... SOURCE [DEST]')),
2257 "qcommit|qci":
2257 "qcommit|qci":
2258 (commit,
2258 (commit,
2259 commands.table["^commit|ci"][1],
2259 commands.table["^commit|ci"][1],
2260 _('hg qcommit [OPTION]... [FILE]...')),
2260 _('hg qcommit [OPTION]... [FILE]...')),
2261 "^qdiff":
2261 "^qdiff":
2262 (diff,
2262 (diff,
2263 [('g', 'git', None, _('use git extended diff format')),
2263 [('g', 'git', None, _('use git extended diff format')),
2264 ('U', 'unified', 3, _('number of lines of context to show')),
2264 ('U', 'unified', 3, _('number of lines of context to show')),
2265 ] + commands.walkopts,
2265 ] + commands.walkopts,
2266 _('hg qdiff [-I] [-X] [-U NUM] [-g] [FILE]...')),
2266 _('hg qdiff [-I] [-X] [-U NUM] [-g] [FILE]...')),
2267 "qdelete|qremove|qrm":
2267 "qdelete|qremove|qrm":
2268 (delete,
2268 (delete,
2269 [('k', 'keep', None, _('keep patch file')),
2269 [('k', 'keep', None, _('keep patch file')),
2270 ('r', 'rev', [], _('stop managing a revision'))],
2270 ('r', 'rev', [], _('stop managing a revision'))],
2271 _('hg qdelete [-k] [-r REV]... [PATCH]...')),
2271 _('hg qdelete [-k] [-r REV]... [PATCH]...')),
2272 'qfold':
2272 'qfold':
2273 (fold,
2273 (fold,
2274 [('e', 'edit', None, _('edit patch header')),
2274 [('e', 'edit', None, _('edit patch header')),
2275 ('k', 'keep', None, _('keep folded patch files')),
2275 ('k', 'keep', None, _('keep folded patch files')),
2276 ] + commands.commitopts,
2276 ] + commands.commitopts,
2277 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...')),
2277 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...')),
2278 'qgoto':
2278 'qgoto':
2279 (goto,
2279 (goto,
2280 [('f', 'force', None, _('overwrite any local changes'))],
2280 [('f', 'force', None, _('overwrite any local changes'))],
2281 _('hg qgoto [OPTION]... PATCH')),
2281 _('hg qgoto [OPTION]... PATCH')),
2282 'qguard':
2282 'qguard':
2283 (guard,
2283 (guard,
2284 [('l', 'list', None, _('list all patches and guards')),
2284 [('l', 'list', None, _('list all patches and guards')),
2285 ('n', 'none', None, _('drop all guards'))],
2285 ('n', 'none', None, _('drop all guards'))],
2286 _('hg qguard [-l] [-n] [PATCH] [+GUARD]... [-GUARD]...')),
2286 _('hg qguard [-l] [-n] [PATCH] [+GUARD]... [-GUARD]...')),
2287 'qheader': (header, [], _('hg qheader [PATCH]')),
2287 'qheader': (header, [], _('hg qheader [PATCH]')),
2288 "^qimport":
2288 "^qimport":
2289 (qimport,
2289 (qimport,
2290 [('e', 'existing', None, 'import file in patch dir'),
2290 [('e', 'existing', None, 'import file in patch dir'),
2291 ('n', 'name', '', 'patch file name'),
2291 ('n', 'name', '', 'patch file name'),
2292 ('f', 'force', None, 'overwrite existing files'),
2292 ('f', 'force', None, 'overwrite existing files'),
2293 ('r', 'rev', [], 'place existing revisions under mq control'),
2293 ('r', 'rev', [], 'place existing revisions under mq control'),
2294 ('g', 'git', None, _('use git extended diff format'))],
2294 ('g', 'git', None, _('use git extended diff format'))],
2295 _('hg qimport [-e] [-n NAME] [-f] [-g] [-r REV]... FILE...')),
2295 _('hg qimport [-e] [-n NAME] [-f] [-g] [-r REV]... FILE...')),
2296 "^qinit":
2296 "^qinit":
2297 (init,
2297 (init,
2298 [('c', 'create-repo', None, 'create queue repository')],
2298 [('c', 'create-repo', None, 'create queue repository')],
2299 _('hg qinit [-c]')),
2299 _('hg qinit [-c]')),
2300 "qnew":
2300 "qnew":
2301 (new,
2301 (new,
2302 [('e', 'edit', None, _('edit commit message')),
2302 [('e', 'edit', None, _('edit commit message')),
2303 ('f', 'force', None, _('import uncommitted changes into patch')),
2303 ('f', 'force', None, _('import uncommitted changes into patch')),
2304 ('g', 'git', None, _('use git extended diff format')),
2304 ('g', 'git', None, _('use git extended diff format')),
2305 ] + commands.walkopts + commands.commitopts + headeropts,
2305 ] + commands.walkopts + commands.commitopts + headeropts,
2306 _('hg qnew [-e] [-m TEXT] [-l FILE] [-f] PATCH [FILE]...')),
2306 _('hg qnew [-e] [-m TEXT] [-l FILE] [-f] PATCH [FILE]...')),
2307 "qnext": (next, [] + seriesopts, _('hg qnext [-s]')),
2307 "qnext": (next, [] + seriesopts, _('hg qnext [-s]')),
2308 "qprev": (prev, [] + seriesopts, _('hg qprev [-s]')),
2308 "qprev": (prev, [] + seriesopts, _('hg qprev [-s]')),
2309 "^qpop":
2309 "^qpop":
2310 (pop,
2310 (pop,
2311 [('a', 'all', None, _('pop all patches')),
2311 [('a', 'all', None, _('pop all patches')),
2312 ('n', 'name', '', _('queue name to pop')),
2312 ('n', 'name', '', _('queue name to pop')),
2313 ('f', 'force', None, _('forget any local changes'))],
2313 ('f', 'force', None, _('forget any local changes'))],
2314 _('hg qpop [-a] [-n NAME] [-f] [PATCH | INDEX]')),
2314 _('hg qpop [-a] [-n NAME] [-f] [PATCH | INDEX]')),
2315 "^qpush":
2315 "^qpush":
2316 (push,
2316 (push,
2317 [('f', 'force', None, _('apply if the patch has rejects')),
2317 [('f', 'force', None, _('apply if the patch has rejects')),
2318 ('l', 'list', None, _('list patch name in commit text')),
2318 ('l', 'list', None, _('list patch name in commit text')),
2319 ('a', 'all', None, _('apply all patches')),
2319 ('a', 'all', None, _('apply all patches')),
2320 ('m', 'merge', None, _('merge from another queue')),
2320 ('m', 'merge', None, _('merge from another queue')),
2321 ('n', 'name', '', _('merge queue name'))],
2321 ('n', 'name', '', _('merge queue name'))],
2322 _('hg qpush [-f] [-l] [-a] [-m] [-n NAME] [PATCH | INDEX]')),
2322 _('hg qpush [-f] [-l] [-a] [-m] [-n NAME] [PATCH | INDEX]')),
2323 "^qrefresh":
2323 "^qrefresh":
2324 (refresh,
2324 (refresh,
2325 [('e', 'edit', None, _('edit commit message')),
2325 [('e', 'edit', None, _('edit commit message')),
2326 ('g', 'git', None, _('use git extended diff format')),
2326 ('g', 'git', None, _('use git extended diff format')),
2327 ('s', 'short', None, _('refresh only files already in the patch')),
2327 ('s', 'short', None, _('refresh only files already in the patch')),
2328 ] + commands.walkopts + commands.commitopts + headeropts,
2328 ] + commands.walkopts + commands.commitopts + headeropts,
2329 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...')),
2329 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...')),
2330 'qrename|qmv':
2330 'qrename|qmv':
2331 (rename, [], _('hg qrename PATCH1 [PATCH2]')),
2331 (rename, [], _('hg qrename PATCH1 [PATCH2]')),
2332 "qrestore":
2332 "qrestore":
2333 (restore,
2333 (restore,
2334 [('d', 'delete', None, _('delete save entry')),
2334 [('d', 'delete', None, _('delete save entry')),
2335 ('u', 'update', None, _('update queue working dir'))],
2335 ('u', 'update', None, _('update queue working dir'))],
2336 _('hg qrestore [-d] [-u] REV')),
2336 _('hg qrestore [-d] [-u] REV')),
2337 "qsave":
2337 "qsave":
2338 (save,
2338 (save,
2339 [('c', 'copy', None, _('copy patch directory')),
2339 [('c', 'copy', None, _('copy patch directory')),
2340 ('n', 'name', '', _('copy directory name')),
2340 ('n', 'name', '', _('copy directory name')),
2341 ('e', 'empty', None, _('clear queue status file')),
2341 ('e', 'empty', None, _('clear queue status file')),
2342 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2342 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2343 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]')),
2343 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]')),
2344 "qselect":
2344 "qselect":
2345 (select,
2345 (select,
2346 [('n', 'none', None, _('disable all guards')),
2346 [('n', 'none', None, _('disable all guards')),
2347 ('s', 'series', None, _('list all guards in series file')),
2347 ('s', 'series', None, _('list all guards in series file')),
2348 ('', 'pop', None, _('pop to before first guarded applied patch')),
2348 ('', 'pop', None, _('pop to before first guarded applied patch')),
2349 ('', 'reapply', None, _('pop, then reapply patches'))],
2349 ('', 'reapply', None, _('pop, then reapply patches'))],
2350 _('hg qselect [OPTION]... [GUARD]...')),
2350 _('hg qselect [OPTION]... [GUARD]...')),
2351 "qseries":
2351 "qseries":
2352 (series,
2352 (series,
2353 [('m', 'missing', None, _('print patches not in series')),
2353 [('m', 'missing', None, _('print patches not in series')),
2354 ] + seriesopts,
2354 ] + seriesopts,
2355 _('hg qseries [-ms]')),
2355 _('hg qseries [-ms]')),
2356 "^strip":
2356 "^strip":
2357 (strip,
2357 (strip,
2358 [('f', 'force', None, _('force removal with local changes')),
2358 [('f', 'force', None, _('force removal with local changes')),
2359 ('b', 'backup', None, _('bundle unrelated changesets')),
2359 ('b', 'backup', None, _('bundle unrelated changesets')),
2360 ('n', 'nobackup', None, _('no backups'))],
2360 ('n', 'nobackup', None, _('no backups'))],
2361 _('hg strip [-f] [-b] [-n] REV')),
2361 _('hg strip [-f] [-b] [-n] REV')),
2362 "qtop": (top, [] + seriesopts, _('hg qtop [-s]')),
2362 "qtop": (top, [] + seriesopts, _('hg qtop [-s]')),
2363 "qunapplied": (unapplied, [] + seriesopts, _('hg qunapplied [-s] [PATCH]')),
2363 "qunapplied": (unapplied, [] + seriesopts, _('hg qunapplied [-s] [PATCH]')),
2364 }
2364 }
General Comments 0
You need to be logged in to leave comments. Login now