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